How to Add a New Line of Text to an Existing File in Java

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

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
}
}

Java: How to add a new line of String to the existing text file?

Use PrintWriter output = new PrintWriter(new FileWriter(highscore, true)); instead of PrintWriter output = new PrintWriter(highscore);

As the second argument in the constructor tells the FileWriter to
append the input to the file rather than overwriting it.

 public class StreamFilter {

public static void main(String[] args) {
System.out.print("Enter Your Name: ");
Scanner inputName = new Scanner(System.in);
String score="hui";
String name = inputName.nextLine();

try {
File highscore = new File("highscore.txt");

PrintWriter output = new PrintWriter(highscore);//remove this
PrintWriter output = new PrintWriter(new FileWriter(highscore, true));//usethis,
if (highscore.exists()) {
System.out.println("Score has been saved!");
}
output.println(name + " - " + score);
output.close();

} catch (IOException e) {
System.out.println(e);
}
}
}

Files.write() : appending new lines in a text file

You should avoid specific new line separators such as "\n" or "\r\n" that depends on the OS and favor the use of the System.lineSeparator() constant that applies at runtime the separator of the OS on which the JVM runs.

how can I add new lines in txt using java, and without empty spaces

How about use BufferedWriter instead of PrintWriter?

It's my sample code. please try test below code.

import java.io.*;

public class Stackoverflow {
public static void main(String[] args) {
File file = new File("C:\\test.txt");
OutputStream outputStream = null;
Writer writer = null;
BufferedWriter bufferedWriter = null;

try {
outputStream = new FileOutputStream(file);
writer = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(writer);

bufferedWriter.write("Hello");
bufferedWriter.write("\r\n");
bufferedWriter.write("\r\n");
bufferedWriter.write("Bye");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (Exception ignore) {

}
}

if (writer != null) {
try {
writer.close();
} catch (Exception ignore) {

}
}

if (outputStream != null) {
try {
outputStream.close();
} catch (Exception ignore) {

}
}
}

}
}

output

Hello

Bye


Related Topics



Leave a reply



Submit