728x90 AdSpace

Saturday, 5 October 2013

How to write file using FileOutputStream in Java


In this tutorials we are going to see how to write file using FileOutputStream in Java.
1.Create project called JavaMisc.
2.Create package called com.javatutorialscorner.io Create java class called FileWriter under com.javatutorialscorner.io package.
FileWriter.java
package com.javatutorialscorner.io;

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

public class FileWriter {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
FileOutputStream fos = null;
String message = "This is test String to be written in File named JavaTutorialsCorner";
File file = null;
try {
file = new File("C:\\jtc\\javatutorialscorner.txt");
fos = new FileOutputStream(file);

if (!file.exists()) {
file.createNewFile();
}

byte[] bytes = message.getBytes();
fos.write(bytes);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

The FileOutputStream class  is a bytes stream class that used to handle raw binary data.

Now run the program see the file created at specified location with text given below.

This is test String to be written in File named JavaTutorialsCorner
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to write file using FileOutputStream in Java Rating: 5 Reviewed By: Annamalai Thangaraj