How to write to file in Java – FileOutputStream

In Java, FileOutputStream is a bytes stream class that’s used to handle raw binary data. To write the data to file, you have to convert the data into bytes and save it to file. See below full example.


package com.mkyong.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
	public static void main(String[] args) {

		FileOutputStream fop = null;
		File file;
		String content = "This is the text content";

		try {

			file = new File("c:/newfile.txt");
			fop = new FileOutputStream(file);

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// get the content in bytes
			byte[] contentInBytes = content.getBytes();

			fop.write(contentInBytes);
			fop.flush();
			fop.close();

			System.out.println("Done");

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fop != null) {
					fop.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

An updated JDK7 example, using new “try resource close” method to handle file easily.


package com.mkyong.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
	public static void main(String[] args) {

		File file = new File("c:/newfile.txt");
		String content = "This is the text content";

		try (FileOutputStream fop = new FileOutputStream(file)) {

			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// get the content in bytes
			byte[] contentInBytes = content.getBytes();

			fop.write(contentInBytes);
			fop.flush();
			fop.close();

			System.out.println("Done");

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

References

  1. http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html
  2. https://mkyong.com/java/how-to-read-file-in-java-fileinputstream/

18 comments on “How to write to file in Java – FileOutputStream

  1. Wouldn’t that write the text all one line; even if content included a larger amount of text on different lines? I’m working in similar code and trying to write to file using text from a TextField but it put all the text on one line. Anyone know how to solve that issue?

    Thanks
    Steven

    Reply
  2. Good post – I found this because BufferedWriter has a bug in it that causes memory leaks if you don’t do System.gc()… needed to figure out the best way to write to file using FileOutputStream. This was helpful.

    Reply
  3. Hi, I want to write a result in Excel sheet row by row, can you help me please……….

    Reply
  4. Great thanks, you’re posting really helpful and working examples! Best wishes for you!

    Reply
  5. Hi,
    you are the Best, I like you very much 🙂

    I whish you all the best.
    🙂

    Reply
  6. Excuse me why are you closing() fop _twice_ (in both examples) ?

    Reply
  7. But it doesn’t work. Is there a simple way to read the content and retrieve it using java?

    Reply
  8. I stored a path to a zip file (full path) in my database and defined its data type as a text. I want to retrieve it using Java. I used the following to retrieve this zip:

    source.code.myproject.DBConnection dbconn = new source.code.myproject.DBConnection();
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement ps = null;
    Statement st = null;
    String redirectURL = null;
    conn = dbconn.setConnection();
    String packageName = null;
    //String scopeDefinition = null;
    FileOutputStream fos=null;
    InputStream isoutput = null;
    String output = null;
    String strquery = “SELECT AName, Aspect_Package FROM Aspect WHERE AName=’NumOfExecution’ “;
    ps = dbconn.precompiled(strquery, conn);
    rs = ps.executeQuery();
    try{
    if(rs.next()){
    isoutput = rs.getBinaryStream(“Aspect_Package”);
    packageName = rs.getString(“AName”);
    fos = new FileOutputStream(new File(Path to “C:\\” +(packageName)+ “Your Extension(.zip)”));

    }
    //redirectURL = “success.jsp”;
    // response.sendRedirect(redirectURL);
    }
    catch(Exception e){
    out.println(“Deployment Error: “+ e);
    }

    dbconn.CloseConn(rs, st, ps, conn);

    Reply
  9. Love your tutorials.Simple and straight to the point.I have a question though,how do i write to multiple files? for example, write different messages to more than one file.
    e.g:
    String content=”Hello World”;
    goes to C:\\greetings.txt
    String secondContent=”Come on, i said hello world”;
    goes to C:\\angryGreeting.txt

    Reply
    1. make multiple ‘File’ objects and link them to their respective ‘FileOutputStream’ objects and follow the same method as mentioned above.

      Reply
  10. Does the same 🙂
    PrintWriter f = new PrintWriter(path);
    f.println(out);
    f.close();

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *