Java write to file append to file

Appending to a File in Java

Learn to append the data to a file in Java using BufferedWritter, PrintWriter, FileOutputStream and Files classes. In all the examples, while opening the file to write, we have passed a second argument as true which denotes that the file needs to be opened in append mode.

With Files class, we can write a file using it’s write() function. Internally write() function uses OutputStream to write byte array into the file.

To append content to an existing file, Use StandardOpenOption.APPEND while writing the content.

String textToAppend = "Happy Learning !!"; Path path = Paths.get("c:/temp/samplefile.txt"); Files.write(path, textToAppend.getBytes(), StandardOpenOption.APPEND); 

BufferedWriter buffers the data in an internal byte array before writing to the file, so it results in fewer IO operations and improves the performance.

To append a string to an existing file, open the writer in append mode and pass the second argument as true .

String textToAppend = "Happy Learning !!"; Strinng filePath = "c:/temp/samplefile.txt"; try(FileWriter fw = new FileWriter(filePath, true); BufferedWriter writer = new BufferedWriter(fw);)

We can use the PrintWriter to write formatted text to a file. PrintWriter implements all of the print() methods found in PrintStream , so we can use all formats which you use with System.out.println() statements.

To append content to an existing file, open the writer in append mode by passing the second argument as true .

String textToAppend = "Happy Learning !!"; String fileName = "c:/temp/samplefile.txt"; try(FileWriter fileWriter = new FileWriter(fileName, true); PrintWriter printWriter = new PrintWriter(fileWriter);)

Use FileOutputStream to write binary data to a file. FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter .

To append content to an existing file, open FileOutputStream in append mode by passing the second argument as true .

String textToAppend = "\r\n Happy Learning !!"; String fileName = "c:/temp/samplefile.txt"; try(FileOutputStream outputStream = new FileOutputStream(fileName, true))

Источник

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.

Читайте также:  Making matrices in python

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.

Источник

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).

Читайте также:  Java create random int

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.

Источник

Append to a file in java using BufferedWriter, PrintWriter, FileWriter

In this tutorial we will learn how to append content to a file in Java. There are two ways to append:

1) Using FileWriter and BufferedWriter : In this approach we will be having the content in one of more Strings and we will be appending those Strings to the file. The file can be appended using FileWriter alone however using BufferedWriter improves the performance as it maintains a buffer.
2) Using PrintWriter : This is one of best way to append content to a file. Whatever you write using PrintWriter object would be appended to the File.

1) Append content to File using FileWriter and BufferedWriter

import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo < public static void main( String[] args ) < try< String content = "This is my content which would be appended " + "at the end of the specified file"; //Specify the file name and path here File file =new File("C://myfile.txt"); /* This logic is to create the file if the * file is not already present */ if(!file.exists())< file.createNewFile(); >//Here true is to append the content to file FileWriter fw = new FileWriter(file,true); //BufferedWriter writer give better performance BufferedWriter bw = new BufferedWriter(fw); bw.write(content); //Closing BufferedWriter Stream bw.close(); System.out.println("Data successfully appended at the end of file"); >catch(IOException ioe) < System.out.println("Exception occurred:"); ioe.printStackTrace(); >> >
Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my fileThis is my content which would be appended at the end of the specified file

2) Append content to File using PrintWriter

PrintWriter gives you more flexibility. Using this you can easily format the content which is to be appended to the File .

import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo2 < public static void main( String[] args ) < try< File file =new File("C://myfile.txt"); if(!file.exists())< file.createNewFile(); >FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter pw = new PrintWriter(bw); //This will add a new line to the file content pw.println(""); /* Below three statements would add three * mentioned Strings to the file in new lines. */ pw.println("This is first line"); pw.println("This is the second line"); pw.println("This is third line"); pw.close(); System.out.println("Data successfully appended at the end of file"); >catch(IOException ioe) < System.out.println("Exception occurred:"); ioe.printStackTrace(); >> >
Data successfully appended at the end of file

Lets say myfile.txt content was:

This is the already present content of my file

After running the above program the content would be:

This is the already present content of my file This is first line This is the second line This is third line

References:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Thank you so much Sir! I was actually creating a program in which I needed to create a file once and for all and keep adding data later. But somehow it always created a new file whenever I executed it. My problem is finally solved. Thank you very very very much Sir.

Using FileWriter can i write the key value pair(username = “login_data”) data to a (properties) “config.properties” file instead of .txt file. Thanks in advance 🙂

Источник

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