tags:

views:

955

answers:

4

Can we rename a file say test.txt to test1.txt? What if test1.txt exists will it rename? How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?

+1  A: 

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

About renaming a file in Java, see the documentation for the renameTo() method in class File.

Yuval
+2  A: 

You want to utilize the renameTo method on a File object.

First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.

If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.

Thomas Owens
And what's wrong with this?
Thomas Owens
This gets downvoted? Why?
Mnementh
No idea, but it's the exact same thing that Pierre posted, without the source code...
Thomas Owens
+1  A: 

copied from http://www.exampledepot.com/egs/java.io/RenameFile.html

// File (or directory) with old name
    File file = new File("oldname");

    // File (or directory) with new name
    File file2 = new File("newname");
    if(file2.exists()) throw new java.IOException("file exists");

    // Rename file (or directory)
    boolean success = file.renameTo(file2);
    if (!success) {
        // File was not successfully renamed
    }

to append to the new file:

java.io.FileWriter out= new java.io.FileWriter(file2, true /** append=yes */);
Pierre
This code won't work in all cases or platforms. The rename to method is not reliable: http://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows
Stephane Grenier
+1  A: 

If it's just renaming the file, you can use File.renameTo().

In the case where you want to append the contents of the second file to the first, take a look at FileOutputStream with the append constructor option or The same thing for FileWriter. You'll need to read the contents of the file to append and write them out using the output stream/writer.

Dan Vinton