Java

Writing Data into File using Java NIO

In this tutorial we are going to learn how to write data into 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.

WriteToFile.java

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


public class WriteToFile
{
    public static void main(String[] args)
    {
        try
        {
            //Writing with Bytes


            Path path=Paths.get("destination\\abc.txt");
            String content="Hey Coding Owls!!";
            Files.write(path, content.getBytes());


             //Writing with List of String


             Path path1=Paths.get("destination\\data1.txt");
            
             List contentInList=new ArrayList<>();


             contentInList.add("Twinkle, twinkle, little star");
             contentInList.add("How I wonder what you are");
             contentInList.add("Up above the world so high");
             contentInList.add("Like a diamond in the sky");
             contentInList.add("Twinkle, twinkle little star");
             contentInList.add("How I wonder what you are");


             Files.write(path1, contentInList);           
          
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Related Posts

Table Of Contents

;