Home > Java > javaTutorial > How Do I Rename and Append to Files in Java?

How Do I Rename and Append to Files in Java?

Mary-Kate Olsen
Release: 2024-12-21 08:47:11
Original
277 people have browsed it

How Do I Rename and Append to Files in Java?

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);
Copy after login

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:

  1. Rename the first file to the existing file's name.
  2. Create a new FileWriter with the append parameter set to true.
  3. Write the contents of the first file to the FileWriter.
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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template