Java appending to text file

How to append text to file in Java? Example Tutorial

Hello guys, In this article, I’ll teach you how to append text to a file in Java. Earlier, I have taught you guys how to create a file and write text into it, but, append is totally different than creating a new file and writing data into it. In the case of append, the file already exists and you just add text at the end of the file. One popular example of appending text into a file is a log file that is constantly updated because your application continuously appends log details into it. While you don’t need to create a logging framework here, just knowing how to append text into an existing file in Java is useful for Java programmers of all kinds of experience.

Here is how the file looked like before and after executing this Java program.

Top 5 Technology Companies in World Apple Google Amazon Microsoft Cisco
Top 5 Technology Companies in World Apple Google Amazon Microsoft Cisco Facebook Twitter

How to append text to a file in Java? Example

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream .

Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing objects) at a time. In such situations, the constructors in this class will fail if the file involved is already open.

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream . If you want to learn more about Java IO API, I suggest you pick a comprehensive Java course like these best Java Programming courses which contains the best Java courses from Udmey, Coursera, Pluralsight, and other popular websites.

Exception in thread "main" java.lang.NullPointerException at java.io.Writer.(Writer.java:88) at java.io.BufferedWriter.(BufferedWriter.java:101) at java.io.BufferedWriter.(BufferedWriter.java:88) at Testing.main(Testing.java:18)
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * Java Program to append text to file. * @author */ public class JavaFileAppendExample < public static void main(String args[]) < FileWriter fw = null; BufferedWriter bfw = null; try < //fw = new FileWriter("data.txt"); //This will overwrite // existing file fw = new FileWriter("data.txt", true); bfw = new BufferedWriter(fw); bfw.write("Facebook"); bfw.write("Twitter"); bfw.flush(); System.out.println("Successfully, text appended to file"); > catch (IOException failure) < // handle error > finally < // close files and streams try < if (fw != null) < fw.close(); >> catch (IOException failed) < /* can't do anything */ > try < if (bfw != null) < bfw.close(); >> catch (IOException failed) < /* can't do anything */ > > > >
System.out.println("text appended to file");
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; /** * * @author */ public class Testing < public static void main(String args[]) < try (FileWriter fw = new FileWriter("data.txt", true); BufferedWriter bfw = new BufferedWriter(fw);) < bfw.write("\nFacebook"); bfw.write("\nTwitter"); bfw.flush(); System.out.println("text appended to file"); > catch (IOException failure) < // handle error > > >
text appended to file File after execution: Top 5 Technology Companies in World Apple Google Amazon Microsoft Cisco Facebook Twitter

In Java 7, by using try-with-resources statements for automatic resource cleanup, this code will be much shorter.

  • How to convert JSON array to String array in Java using Gson? (tutorial)
  • 6 Courses to learn Spring in depth (courses)
  • How to Escape JSON String in Eclipse (tips)
  • How to ignore Unknown properties while parsing JSON in Java? (tutorial)
  • 3 ways to convert String to JSON object in Java? (tutorial)
  • 5 JSON libraries Java JEE Programmer should know (list)
  • Why use Spring to create REST API in Java? (article)
  • How to parse JSON with the date field in Java using Jackson? (tutorial)
  • How to download the Jackson library for JSON parsing? (tutorial)
  • How to convert a JSON Array to String Array in Java? (tutorial)
  • How to parse a large JSON file using Jackson Streaming API? (example)
  • How to use Google Protocol Buffer (protobuf) in Java? (tutorial)
  • Top 5 courses to learn Spring boot in-depth (courses)
  • Top 10 RESTful Web Service Interview Questions (see here)
  • What is the purpose of different HTTP methods in REST? (see here)
  • 5 Courses to learn RESTFul Web Services in Java? (courses)
Читайте также:  WORKING WITH FILES [encode/decode]

Thanks for reading this article so far. If you like this Jackson tutorial to parse CSV file in Java then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. — If you are new to Java and looking for some free courses to start with then you can also check out this list of free Java Courses for Beginners. Join them before they expire.

Источник

How to append text to a file in Java

In this quick article, I’ll show you how to append text to an existing file using Java legacy I/O API as well as non-blocking new I/O API (NIO).

The simplest and most straightforward way of appending text to an existing file is to use the Files.write() static method. This method is a part of Java’s new I/O API (classes in java.nio.* package) and requires Java 7 or higher. Here is an example that uses Files.write() to append data to a file:

try  // append data to a file Files.write(Paths.get("output.txt"), "Hey, there!".getBytes(), StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append Hey, there! to a file called output.txt . If the file doesn’t exist, it will throw a NoSuchFileException exception. It also doesn’t append a new line automatically which is often required when appending to a text file. If you want to create a new file if it doesn’t already exist and also append new line automatically, use another variant of Files.write() as shown below:

try  // data to append ListString> contents = Arrays.asList("Hey, there!", "What's up?"); // append data to a file Files.write(Paths.get("output.txt"), contents, StandardOpenOption.CREATE, StandardOpenOption.APPEND); > catch (IOException ex)  ex.printStackTrace(); > 

If the file has encoding other than the default character encoding of the operating system, you can specify it like below:

Files.write(Paths.get("output.txt"), contents, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

Note: Files.write() is good if you want to append to a file once or a few times only. Because it opens and writes the file every time to the disk, which is a slow operation. For frequent append requests, you should rather BufferedWriter (explained below).

The BufferedWriter class is a part of Java legacy I/O API that can also be used to append text to a file. Here is an example that uses the Files.newBufferedWriter() static method to create a new writer (require Java 8+):

try  // create a writer BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.APPEND); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The above code will append text to file. If the file doesn’t already exist, it will throw a NoSuchFileException exception. However, you can change it to create a new file if not available with the following:

BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardOpenOption.CREATE, StandardOpenOption.APPEND); 
BufferedWriter bw = Files.newBufferedWriter(Paths.get("output.txt"), StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); 

If you are using Java 7 or below, you can use FileWriter wrapped in a BufferedWriter object to append data to a file as shown below:

try  // create a writer BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true)); // append text to file bw.write("Hey, there!"); bw.newLine(); bw.write("What's up?"); // close the writer bw.close(); > catch (IOException ex)  ex.printStackTrace(); > 

The second argument to the FileWriter constructor will tell it to append data to the file, rather than writing a new file. If the file does not already exist, it will be created.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Java append to file

Java append to file

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will look into how to append to a file in java. Java append to file is a common java IO operation. For example, whenever we print something to server logs, it gets appended to the existing file.

Java append to file

  1. Java append to file using FileWriter
  2. Java append content to existing file using BufferedWriter
  3. Append text to file in java using PrintWriter
  4. Append to file in java using FileOutputStream

java append to file

If you are working on text data and the number of write operations is less, use FileWriter and use its constructor with append flag value as true . If the number of write operations is huge, you should use the BufferedWriter. To append binary or raw stream data to an existing file, you should use FileOutputStream.

Java append to file using FileWriter

Here is the short program to append to file in java using FileWriter. We will look into a complete Java append to file example program later on.

File file = new File("append.txt"); FileWriter fr = new FileWriter(file, true); fr.write("data"); fr.close(); 

Java append content to existing file using BufferedWriter

File file = new File("append.txt"); FileWriter fr = new FileWriter(file, true); BufferedWriter br = new BufferedWriter(fr); br.write("data"); br.close(); fr.close(); 

Append text to file in java using PrintWriter

We can also use PrintWriter to append to file in java.

File file = new File("append.txt"); FileWriter fr = new FileWriter(file, true); BufferedWriter br = new BufferedWriter(fr); PrintWriter pr = new PrintWriter(br); pr.println("data"); pr.close(); br.close(); fr.close(); 

Append to file in java using FileOutputStream

You should use FileOutputStream to append data to file when it’s raw data, binary data, images, videos etc.

OutputStream os = new FileOutputStream(new File("append.txt"), true); os.write("data".getBytes(), 0, "data".length()); os.close(); 

Java append to file example

Here is the final java append to file program showing all the different options we discussed above.

package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; public class JavaAppendToFile < /** * Java append to file example * * @param args */ public static void main(String[] args) < String filePath = "/Users/pankaj/Downloads/append.txt"; String appendText = "This String will be appended to the file, Byte=0x0A 0xFF"; appendUsingFileWriter(filePath, appendText); appendUsingBufferedWriter(filePath, appendText, 2); appendUsingPrintWriter(filePath, appendText); appendUsingFileOutputStream(filePath, appendText); >private static void appendUsingPrintWriter(String filePath, String text) < File file = new File(filePath); FileWriter fr = null; BufferedWriter br = null; PrintWriter pr = null; try < // to append to file, you need to initialize FileWriter using below constructor fr = new FileWriter(file, true); br = new BufferedWriter(fr); pr = new PrintWriter(br); pr.println(text); >catch (IOException e) < e.printStackTrace(); >finally < try < pr.close(); br.close(); fr.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use Stream for java append to file when you are dealing with raw data, binary * data * * @param data */ private static void appendUsingFileOutputStream(String fileName, String data) < OutputStream os = null; try < // below true flag tells OutputStream to append os = new FileOutputStream(new File(fileName), true); os.write(data.getBytes(), 0, data.length()); >catch (IOException e) < e.printStackTrace(); >finally < try < os.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use BufferedWriter when number of write operations are more * * @param filePath * @param text * @param noOfLines */ private static void appendUsingBufferedWriter(String filePath, String text, int noOfLines) < File file = new File(filePath); FileWriter fr = null; BufferedWriter br = null; try < // to append to file, you need to initialize FileWriter using below constructor fr = new FileWriter(file, true); br = new BufferedWriter(fr); for (int i = 0; i < noOfLines; i++) < br.newLine(); // you can use write or append method br.write(text); >> catch (IOException e) < e.printStackTrace(); >finally < try < br.close(); fr.close(); >catch (IOException e) < e.printStackTrace(); >> > /** * Use FileWriter when number of write operations are less * * @param filePath * @param text * @param noOfLines */ private static void appendUsingFileWriter(String filePath, String text) < File file = new File(filePath); FileWriter fr = null; try < // Below constructor argument decides whether to append or override fr = new FileWriter(file, true); fr.write(text); >catch (IOException e) < e.printStackTrace(); >finally < try < fr.close(); >catch (IOException e) < e.printStackTrace(); >> > > 

That’s all for append to file in java program.

You can checkout more Java IO examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью