How to Append Text to an Existing File in Java

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 as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter 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:

Sample Image

After demo.txt file:

Sample Image

Explanation:

  1. Reading data line by line from file demo.txt file.
  2. Updated Line 7 and replace admin HOST with admin HOST Test.
  3. 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



Leave a reply



Submit