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();
}
}
}
Hi,
you are the Best, I like you very much 🙂
I whish you all the best.
🙂
many program not run
ty 4 this useful code.
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
is it possible to use relative path?
And to save in UTF8?
Thank you for this!
Hi, I want to write a result in Excel sheet row by row, can you help me please……….
Thanks man
Excuse me why are you closing() fop _twice_ (in both examples) ?
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);
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
make multiple ‘File’ objects and link them to their respective ‘FileOutputStream’ objects and follow the same method as mentioned above.
Does the same 🙂
PrintWriter f = new PrintWriter(path);
f.println(out);
f.close();
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.
Great thanks, you’re posting really helpful and working examples! Best wishes for you!
I like your straight forward and to the point tutorials. These are really helpful to me.
Thanks,
Mansoor
But it doesn’t work. Is there a simple way to read the content and retrieve it using java?