Delete and rename file in java

I created the file "file1" in java and I read "file1" and made some changes to the data read from "file1" and I wrote new data to another file "file2" ... now what I need to delete the previous file " file1 "and change the file name" file2 "to" file1 "... please help me with this ....

+5
source share
5 answers
//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();
+16
source

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

See Javadoc for java.io.File.

+2
source

, Java API (. ):

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

Starting with Java 7 you can use java.nio.file.Files.deleteand 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);
}
+1
source

File.delete () to delete a file, it will return a boolean to indicate the status of the delete operation; true if the file is deleted; false if failed.
file.renameTo (file2) to rename the file, it will return a boolean to indicate the status of the rename operation; 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
source

All Articles