How do I add text to the end of a file in Java?
There is a text file that already stores some information.
How can I add data to a file if the write
method of the FileWritter
class overwrites the old data and writes new ones?
1
2 answers
Method 1:
One option is to use the write method of the Files :
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class Main {
public static void main(String[] args) {
String filePath = "/home/user/Desktop/project/src/myfile.txt";
String text = "Hello world!\n";
try {
Files.write(Paths.get(filePath), text.getBytes(), StandardOpenOption.APPEND);
}
catch (IOException e) {
System.out.println(e);
}
}
}
Method 2:
Using the FileWriter created by the corresponding constructor
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String filePath = "/home/user/Desktop/project/src/myfile.txt";
String text = "Hello world!\n";
try {
FileWriter writer = new FileWriter(filePath, true);
BufferedWriter bufferWriter = new BufferedWriter(writer);
bufferWriter.write(text);
bufferWriter.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
4
Author: LEQADA, 2015-11-04 21:38:44
public FileWriter(String fileName, boolean append) throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:fileName
- String The system-dependent filename.append
- boolean if true, then data will be written to the end of the file rather than the beginning.
Not that?
2
Author: Sergey, 2015-11-04 17:39:18