开发者

delete and rename a file in java

开发者 https://www.devze.com 2023-02-17 16:20 出处:网络
i\'ve created a file \"file1\" in java and i read that \"file1\" and made some changes to the data read from \"file1\" andi wrote the new data to another file \"file2\"...now what i need is to delete

i've created a file "file1" in java and i read that "file1" and made some changes to the data read from "file1" and i wrote the new data to another file "file2"...now what i need is to delete the previous file "file1" 开发者_运维问答and change the name of the file "file2" to "file1"... please somebody help me with this....


//rename file
File file = new File("oldname");
File file2 = new File("newname");
boolean success = file.renameTo(file2);

//delete file
File f = new File("fileToDelete");
boolean success = f.delete();


You can use File.delete() and File.rename(File target) for this purpose.

See the Javadoc for java.io.File.


Basically, Java provides the needed API (See here for more):

file1.delete();
file2.renameTo(file1);


Since Java 7 you can use java.nio.file.Files.delete and java.nio.file.Files.move:

Path path1 = Paths.get("C:\\file1");
Path path2 = Paths.get("C:\\file2");

try {
    Files.delete(path1);
    Files.move(path2, path1);
} catch (IOException e) {
    System.err.println("Something went wrong - " + e);
}


You must remember about two things : The file and the file extension (file type). The following is wrong way sometimes, in case of deleting and renaming file :

File file = new File (dir+"/"+myfile) 

The right way is :

File file = new File (dir, myfile+".db"); 

So you Should pay attention about this two things. Now:

Delete File :

//(check with extension and without extension): 


        File dir = commonDir();
        File subDir = new File(dir + "/Darsul_Quran");
        File alreadyloaded = new File(subDir , fileName + ".db");
        File additionalJournalFile = new File(subDir , fileName + ".db-journal");

        File alreadyloaded2 = new File(subDir , fileName );

        if (alreadyloaded2.exists()) {
            if (alreadyloaded2.delete()) {
                Toast.makeText(mContext, "File Deleted Successfully.", Toast.LENGTH_SHORT).show();
            }
        }

        if (alreadyloaded.exists()) {
            if (alreadyloaded.delete()) {
                Toast.makeText(mContext, "File Deleted Successfully.", Toast.LENGTH_SHORT).show();

                //  fileListArray.remove(fileListPosition);
                // fileAdapter.notifyDataSetChanged();
                refreshList();

                if (additionalJournalFile.exists()) {
                    if (additionalJournalFile.delete()) {
                        // fileAdapter.notifyDataSetChanged();
                        refreshList();
                    }
                }
            } else
                Toast.makeText(mContext, "File Cannot be Deleted.", Toast.LENGTH_SHORT).show();

        } else {

            Toast.makeText(mContext, "File Not Found.", Toast.LENGTH_SHORT).show();
        }

Rename File :

private void renameOneFile(final String fileName) {

        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(mContext);
        builder.setTitle("Rename File:  ");
        builder.setMessage("\n\n"
               // "ফাইলের নতুন নামকরণের জন্য নতুন নামটি লিখুন। এরপর Rename -  এ ক্লিক করুন। "
        );

        final EditText editText = new EditText(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        editText.setLayoutParams(lp);
        editText.setText(fileName);

        builder.setView(editText);

        builder.setPositiveButton("Rename", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {


                File dir = commonDir();
                File subDir = new File(dir + "/Darsul_Quran");
                File alreadyloaded = new File(subDir , fileName + ".db");
                File additionalJournalFile = new File(subDir , fileName + ".db-journal");

                String justRenamedName = editText.getText().toString();

                if (TextUtils.isEmpty(justRenamedName)) {
                    editText.setError("empty");
                    Toast.makeText(mContext, "Please Write new Name", Toast.LENGTH_SHORT).show();
                    return;
                }
                File newRenamedFile = new File(subDir, justRenamedName+ ".db");

                if (alreadyloaded.exists()) {


                   // preparingCopyForRename(alreadyloaded.toString(), justRenamedName+ ".db");

                    if (alreadyloaded.renameTo(newRenamedFile)) { // full path required
                        Toast.makeText(mContext, "Alhamdulillah, File Renamed Successfully.", Toast.LENGTH_SHORT).show();

                        refreshList(justRenamedName);
                        if (additionalJournalFile.exists()) {
                            if (additionalJournalFile.delete()) {
                                // fileAdapter.notifyDataSetChanged();
                                refreshList(justRenamedName);
                            }
                        }
                    } else
                        Toast.makeText(mContext, "File Cannot renamed.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(mContext, "File Not Found.", Toast.LENGTH_SHORT).show();
                }

            }
        });

        builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                dialogInterface.dismiss();
            }
        });

        final androidx.appcompat.app.AlertDialog dialog = builder.create();


        dialog.show();


    }



public static File commonDir() {
        File dir = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            dir = new File(_MyApplication.getContext().getExternalFilesDir(null) + "/tilawaat");
            // dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/tilawaat" );
        } else {
            dir = new File(Environment.getExternalStorageDirectory() + "/tilawaat");
        }

        try {
            if (!dir.exists())
                if(dir.mkdirs())
                    Log.i(TAG, "commonDir: Creating success");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return dir;

    }

This way, you can prevent removing file contents, that happens some time after renaming File.


File.delete() to delete a file, it will return a boolean value to indicate the delete operation status; true if the file is deleted; false if failed.
file.renameTo(file2) to rename a file, it will return a boolean value to indicate the rename operation status; true if the file is renamed; false if failed.

package com.software.file;

    import java.io.File;

    public class RenameAndDeleteFileExample
    {
        public static void main(String[] args)
        {
            try{
                File file = new File("c:\\test.log");
                // File (or directory) with new name
                File file2 = new File("newname");
                //rename file to file2 name
                boolean success = file.renameTo(file2);
                if(file2.delete() && success ){
                    System.out.println(file2.getName() + " is renamed and deleted!");
                }else{
                    System.out.println("operation is failed.");
                }

            }catch(Exception e){

                e.printStackTrace();

            }

        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消