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
0 comments:
Post a Comment