Renaming a File in Java
Java provides a convenient way to rename files using the renameTo() method of the File class. This method takes another File object as an argument, representing the new name of the file.
Overwriting an Existing File
When renaming a file, if a file with the new name already exists, the renameTo() method will throw an IOException with the message "file exists". To handle this scenario, you can use the following code:
File file = new File("test.txt"); File file2 = new File("test1.txt"); if (file2.exists()) { throw new java.io.IOException("file exists"); } boolean success = file.renameTo(file2);
If the renameTo() operation is successful, success will be set to true.
Appending to an Existing File
To append the contents of one file to an existing file, you can follow these steps:
File file = new File("test.txt"); File file2 = new File("test1.txt"); file.renameTo(file2); java.io.FileWriter out = new java.io.FileWriter(file2, true /*append=yes*/); out.write("Hello world!"); out.close();
This code will rename the file test.txt to test1.txt and append the string "Hello world!" to the end of test1.txt.
The above is the detailed content of How Do I Rename and Append to Files in Java?. For more information, please follow other related articles on the PHP Chinese website!