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. http://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
16 Comment threads
2 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
17 Comment authors
priyadavid21gunsSteven Youhanayashvyas07Igor Recent comment authors
newest oldest most voted
ibo
Guest
ibo

Hi,
you are the Best, I like you very much 🙂

I whish you all the best.
🙂

aditi
Guest
aditi

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

Jude
Guest
Jude

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

Areeg
Guest
Areeg

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();… Read more »

Palmer Eldritch
Guest
Palmer Eldritch

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

AdminOfThisBlog
Guest
AdminOfThisBlog

Thanks man

ngowda
Guest
ngowda

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

Zahava A
Guest
Zahava A

Thank you for this!

Igor
Guest
Igor

And to save in UTF8?

yashvyas07
Guest
yashvyas07

is it possible to use relative path?

Steven Youhana
Guest
Steven Youhana

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

david21guns
Guest
david21guns

ty 4 this useful code.

Mansoor Shaikh
Guest
Mansoor Shaikh

I like your straight forward and to the point tutorials. These are really helpful to me.

Thanks,
Mansoor

Ivan
Guest
Ivan

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

Matt Durlin
Guest
Matt Durlin

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.

Areeg
Guest
Areeg

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