English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn various techniques to append Java text to existing files.
Before appending text to an existing file, we assume that insrcThere is a folder namedtest.txtfile.
This istest.txtcontent
This is a Test file.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class AppendFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String text = "Added text"; try { Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { } } }
When running the program,test.txtThe file now contains:
This is a Test file.Added text
In the above program, we use the System.user.dir attribute to get the current directory path stored in the variable. CheckJava program to get the current directory to getMore information.
Similarly, the text to be added is also stored in the variable text. Then, in a try-In the catch block, we use the Files.write() method to append text to the existing file.
The write() method takes the path of the given file, the text to be written to the file, and how to open the file for writing. In our example, we use the APPEND option for writing
Since the write() method may return IOException, we use a try-catch block to correctly catch exceptions.
import java.io.FileWriter; import java.io.IOException; public class AppendFile { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; String text = "Added text"; try { FileWriter fw = new FileWriter(path, true); fw.write(text); fw.close(); } catch (IOException e) { } } }
The output of the program is as follows1Same.
In the above program, we use an instance (object) of FileWriter instead of the write() method to append text to an existing file
When creating the FileWriter object, we pass the file path and true as the second parameter. True indicates that we allow the file to be appended
Then, we use the write() method to append the given text and close the file writer