How to append text to an existing file in Java?
Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.
Java 7+
For a one-time task, the Files class makes this easy:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Careful: The above approach will throw a NoSuchFileException
if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE
and APPEND
options, which will create the file first if it doesn't already exist:
private void write(final String s) throws IOException {
Files.writeString(
Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
s + System.lineSeparator(),
CREATE, APPEND
);
}
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter
is faster:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
//more code
out.println("more text");
//more code
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Notes:
- The second parameter to the
FileWriter
constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a
BufferedWriter
is recommended for an expensive writer (such asFileWriter
). - Using a
PrintWriter
gives you access toprintln
syntax that you're probably used to fromSystem.out
. - But the
BufferedWriter
andPrintWriter
wrappers are not strictly necessary.
Older Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
}
How to add a new line of text to an existing file in Java?
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append)
constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
Append text to existing line in a file
Try this:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Demo {
public static void main(String[] args) throws IOException {
// Update line number 7 and append Test to it
updateLine(7, "Test");
}
public static void updateLine(int lineNumber, String data) throws IOException {
// Path of file
Path path = Paths.get("etc/demo.txt");
// Read all lines
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Update line 7 - Replace admin HOST with admin HOST Test
lines.set(lineNumber - 1, lines.get(lineNumber - 1) + " " + data);
// Write back to the file
Files.write(path, lines, StandardCharsets.UTF_8);
}
}
Before demo.txt file:
After demo.txt file:
Explanation:
- Reading data line by line from file
demo.txt
file. - Updated
Line 7
and replaceadmin HOST
withadmin HOST Test
. - Write data back to the file.
Note: This is an example that will help you to update code as per your requirement.
Appending text to an already existing file at a specific location
If you are simply replacing N with Y i.e. not writing extra information then RandomAccesFile should work for you
see this link for an example of writeChars
How to append existing line in text file
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
how do i append text inside a file using FileWriter
EditText edd = findViewById(R.id.editTextData);
Spinner spp = findViewById(R.id.spinnerCategory);
String text1 = edd.getText().toString();
String text2 = spp.getSelectedItem().toString();
String filename = text2 + ".dat";
try {
File fa = new File(getFilesDir(),filename); //getting the filename path
FileWriter fw = new FileWriter(fa,true);
fw.write(text1 + "\n");
fw.close();
Toast.makeText(getBaseContext(), "Information Saved", Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
} //End try catch statement
Related Topics
Is Short Circuit Evaluation Guaranteed in C++ as It Is in Java
Sending Email in Android Using Javamail API Without Using the Default/Built-In App
How to Paginate Firestore With Android
After Google Play Service Update to Version 13 I Got an Error
Concurrent Modification Exception: Adding to an Arraylist
Android 5.0 - Add Header/Footer to a Recyclerview
What Is a Stack Trace, and How to Use It to Debug My Application Errors
What Is an Efficient Way to Implement a Singleton Pattern in Java
"Implements Runnable" VS "Extends Thread" in Java
How to Fix a Nosuchmethoderror
Why Are Static Variables Considered Evil
Mocking Static Methods With Mockito
Why Is 128==128 False But 127==127 Is True When Comparing Integer Wrappers in Java
How Do Getters and Setters Work