Java

Appending Data to a File using Java NIO

In this tutorial we are going to learn how to append to an already existing file using Java NIO classes of Path and Files, if you are not aware of the methods available with these classes click here.

Steps are very Simple.

Create a Path Object pointing to the file and then use the write() of Files to write the data into the File either using a Byte array or Iterable of String with an additional parameter of StandardOpenOption.APPEND

AppendToFile.java

import java.nio.file.*;
import java.util.*;

public class AppendToFile
{
    public static void main(String[] args)
    {
        try
        {
          Path path=Paths.get("destination\\abc.txt");


          Path sourcePath=Paths.get("data.txt");
          List content=Files.readAllLines(sourcePath);


          for(String line:content)
          {
           
           Files.write(path, line.getBytes(),StandardOpenOption.APPEND);
           Files.write(path,System.getProperty("line.separator").getBytes(),StandardOpenOption.APPEND);
          }
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Related Posts

language_img
Java

Camel Casing Rule

Jul 7, 2020

Table Of Contents

;