How to write to file in Java

Updated on June 23rd, 2018

In this post, we’ll learn different options as How to write to file in Java. We will be covering following options.

  1. Java 7 Files API
  2. BufferWriter.
  3. Apache Commons FileUtils.

 

1.  Java 7 Files API

Java 7  introduced the enhancement to work with the filesystem.Files class provide utility methods to create, delete or move files.

public class WriteFile {

    public static void main(String[] args) throws IOException {

        String fileContent = "We will demo as how to write using Java 7 File API";

        Path path = Paths.get("/tutorials/filewrite/testFile.txt");
        byte[] fileByteContent = fileContent.getBytes();

        Files.write(path, fileByteContent);

        //to validate our data
        String readFile = Files.readAllLines(path).get(0); //we will just read first line
        System.out.println(readFile.equals(fileContent));
    }
}

 

Above programme can be combined with one line

Files.write(Paths.get("/tutorials/filewrite/testFile.txt"), fileContent.getBytes());

Keep in mind following points while using Files Class

  • getBytes() method use default charset (UTF-8), it’s always recommended to pass charset to avoid any surprises.

 

2.  Using BufferWriter

BufferWriter provides the simplified way to write to file in Java. We will check following options to while using BufferWriter

  1. Use BufferWriter with FileOutputStream.
  2. Use BufferWriter with Files Class

In both examples, we will be using Java Try With Resources feature for automatic resource management.

public class WriteFileByBufferedWriter {

    public static void main(String[] args) throws IOException {

        String fileContent = "We will demo as how to write using Java BufferWriter";
        String fileLocation = "tutorials/filewrite/";

        writeFileByOutputStream(fileContent, fileLocation + "file1.txt");
        writeFileUsingFilesBufferedWriter(fileContent, fileLocation + "file2.txt");
    }


    public static void writeFileByOutputStream(final String fileContent, final String fileLocation) throws IOException {

        try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(fileLocation), "UTF-8"))) {
            out.write(fileContent);
        }

    }

    public static void writeFileUsingFilesBufferedWriter(final String fileContent, final String fileLocation) throws IOException {
        Path filePath = Paths.get(fileLocation);
        try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8)) {
            writer.write(fileContent);
        }
    }

 

3.  Append String to Existing File

Buffer writer can be used to append data to an existing file. You need to create BufferReader in Append Mode.

newBufferedWriter(Path path, Charset cs, OpenOption... options),

The options parameter specifies how the file is created or opened. In above example, we created BufferWriter in Append Mode.


public class BufferWriterAppend {

    public static void main(String[] args) throws IOException {

        String fileContent = "This is a demo to show BufferWriter";
        String fileContent1 = " In Append Mode";
        String fileLocation = "/Users/umesh/personal/tutorials/filewrite/sampleFile.txt";

        Path filePath = Paths.get(fileLocation);
        try (BufferedWriter writer = Files.newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
            writer.append(fileContent);
            writer.append(fileContent1);
        }
    }
}

Above code assume that you already have sampleFile.txt in the given location else system will throw NoSuchFileException

4. Using Apache Commons IO 

public class FileByApacheUtils {

    public static void main(String[] args) throws IOException {

        String fileContent = "We will demo as how to write using Java Apache Commons IO Utils";
        FileUtils.write(new File("/tutorials/filewrite/apacheIO.txt"),fileContent, StandardCharsets.UTF_8);
     }
}

In case you need to write a large file, use FileUtils.writeLines() method for the line by line.

We saw some of the most common and popular methods outlining How to write to file in Java. Additional options to write to file in Java.

  1. PrintWriter. (For writing formatted text)
  2. FileOutputStream (Mostly for writing binary data to file)
  3. DataOutputStream.
  4. RandomAccessFile (Ability to write a file at a specific position)
  5. FileChannel

For creating directory read our post on  How to create a directory in Java.

 

All the code of this article is available Over on Github. This is a Maven-based project.

References

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

1
Leave a Reply

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of