Tutorial

Java Write to File - 4 Ways to Write File in Java

Published on August 3, 2022
author

Pankaj

Java Write to File - 4 Ways to Write File in Java

Java provides several ways to write to file. We can use FileWriter, BufferedWriter, java 7 Files and FileOutputStream to write a file in Java.

Java Write to File

java write to file, write file in java Let’s have a brief look at four options we have for java write to file operation.

  1. FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.
  2. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more.
  3. FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java.
  4. Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file.

Java Write to File Example

Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java

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.nio.file.Files;
import java.nio.file.Paths;

public class WriteFile {

    /**
     * This class shows how to write file in java
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) {
        String data = "I will write this String to File in Java";
        int noOfLines = 10000;
        writeUsingFileWriter(data);
        
        writeUsingBufferedWriter(data, noOfLines);
        
        writeUsingFiles(data);
        
        writeUsingOutputStream(data);
        System.out.println("DONE");
    }

    /**
     * Use Streams when you are dealing with raw data
     * @param data
     */
    private static void writeUsingOutputStream(String data) {
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File("/Users/pankaj/os.txt"));
            os.write(data.getBytes(), 0, data.length());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * Use Files class from Java 1.7 to write files, internally uses OutputStream
     * @param data
     */
    private static void writeUsingFiles(String data) {
        try {
            Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Use BufferedWriter when number of write operations are more
     * It uses internal buffer to reduce real IO operations and saves time
     * @param data
     * @param noOfLines
     */
    private static void writeUsingBufferedWriter(String data, int noOfLines) {
        File file = new File("/Users/pankaj/BufferedWriter.txt");
        FileWriter fr = null;
        BufferedWriter br = null;
        String dataWithNewLine=data+System.getProperty("line.separator");
        try{
            fr = new FileWriter(file);
            br = new BufferedWriter(fr);
            for(int i = noOfLines; i>0; i--){
                br.write(dataWithNewLine);
            }
        } 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 data
     */
    private static void writeUsingFileWriter(String data) {
        File file = new File("/Users/pankaj/FileWriter.txt");
        FileWriter fr = null;
        try {
            fr = new FileWriter(file);
            fr.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //close resources
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.

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.

Learn more about our products

About the authors
Default avatar
Pankaj

author

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.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 11, 2021

if path is not available, will it create the directory and filename with extension. whatever we mentioned in path.get() ?

- stephen

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    March 11, 2020

    This would be better to show try-with-resources, as in: try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) { } catch (Exception e) { } // No finally

    - Steve Waring

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 21, 2020

      You have to use the E!

      - Ur Friend

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        January 16, 2020

        I copies the code and put in a text file renaming it with filename being classname and extension .java. When compiling, I am getting this error. What could be the reason. Error: Could not find or load main class *.java Caused by: java.lang.ClassNotFoundException: *.java

        - UNNIKRISHNAN CHANDUVARATH

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          February 6, 2019

          how can I write in the next line using writeusingfilewriter? I know if I add true in (file) I can save any new value, but, how can I do the previous step?

          - Jaffet

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            July 9, 2015

            Hello, Can we store real time output into a text file. I mean that, i am working on NMEA data and this data is continuously coming from GPS device in my computer through USB port, but i am not storing this data into a text file. can we store this real continuous output into a text file in java.

            - Neeraj Jain

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 20, 2014

              explained nice!! but when i try to write some data in file it delete previous data…what should i do if i want to keep previous data…

              - Anang

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                April 14, 2014

                Hi… How can i copy/write the result from the SQLquery of the data base, which is in the form of list (List objList = DBRepositories.getME1Object(dbSession, “H612O2GN” )), in to the file??? Please reply…

                - Danish Nomani

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  December 12, 2013

                  nice tutorial but is it possible to do simultaneous read and write on same file in java ?

                  - wasim

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.