删除并重命名java中的文件

时间:2011-03-19 12:31:13

标签: java file

我在java中创建了一个文件“file1”,我读取了“file1”并对从“file1”读取的数据进行了一些更改,并将新数据写入另一个文件“file2”...现在是什么我需要删除以前的文件“file1”并将文件名“file2”更改为“file1”... 请有人帮我这个....

6 个答案:

答案 0 :(得分:17)

//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();

答案 1 :(得分:2)

您可以将File.delete()File.rename(File target)用于此目的。

请参阅Javadoc了解java.io.File。

答案 2 :(得分:1)

基本上,Java提供了所需的API(更多信息见here):

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

答案 3 :(得分:1)

自Java 7 以来,您可以使用java.nio.file.Files.deletejava.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);
}

答案 4 :(得分:1)

您必须记住两件事:文件和文件扩展名(文件类型)。以下有时是错误的方式,在删除和重命名文件的情况下:

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

正确的做法是:

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

所以你应该注意这两件事。现在:

删除文件:

//(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();
        }

重命名文件:

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;

    }

通过这种方式,您可以防止在重命名文件后一段时间发生删除文件内容。

答案 5 :(得分:0)

File.delete()删除文件,它将返回一个布尔值来指示删除操作状态;如果文件被删除,则为true;如果失败则为假 file.renameTo(file2)重命名文件,它将返回一个布尔值来指示重命名操作状态;如果重命名文件,则为true;如果失败则为假。

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();

            }

        }
    }