Thursday, 10 October 2013

Write File Using FileOutputStream

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("d:/java3.txt");
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();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

No comments:

Post a Comment