Java IO Tutorial

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/

About Author

author image
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

Subscribe
Notify of
18 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
ibo
10 years ago

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

I whish you all the best.
🙂

priya
4 years ago
Reply to  ibo

many program not run

david21guns
6 years ago

ty 4 this useful code.

Steven Youhana
6 years ago

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

yashvyas07
9 years ago

is it possible to use relative path?

Igor
9 years ago

And to save in UTF8?

Zahava A
9 years ago

Thank you for this!

ngowda
10 years ago

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

AdminOfThisBlog
10 years ago

Thanks man

Palmer Eldritch
10 years ago

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

Areeg
10 years ago

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);

Jude
10 years ago

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

Aneesh Kulkarni
9 years ago
Reply to  Jude

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

aditi
11 years ago

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

Matt Durlin
9 years ago

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.

Ivan
10 years ago

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

Mansoor Shaikh
10 years ago

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

Thanks,
Mansoor

Areeg
10 years ago

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