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/
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: great post to read()

  • Pingback: do you agree()

  • Pingback: http://makemoney.camkingz.com/()

  • Pingback: loan payment plan()

  • Pingback: alkaline water()

  • Pingback: alkaline water()

  • Pingback: website()

  • Pingback: alkaline water brands()

  • Pingback: pay day loans()

  • Pingback: best minecraft adventure maps()

  • Pingback: water ionizer()

  • Pingback: free electricians bible()

  • Pingback: house blue()

  • Pingback: water ionizer loan()

  • Pingback: pay per day loans plan()

  • Pingback: Instagram followers kopen()

  • Pingback: water ionizer()

  • Pingback: penge laan nu()

  • Pingback: water ionizer()

  • Pingback: stop parking()

  • Pingback: xnxx()

  • Pingback: car parking()

  • Pingback: Direct TV vs Dish TV()

  • Pingback: Me gusta fisrt.time()

  • Pingback: Blue Coaster33()

  • Ivan

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

  • http://youarethebest ibo

    Hi,
    you are the Best, I like you very much :)

    I whish you all the best.
    :)

  • http://www.linkedin.com/in/mansoorshaikh Mansoor Shaikh

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

    Thanks,
    Mansoor

  • Palmer Eldritch

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

  • Areeg

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

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

  • http://none 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

  • aditi

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