Sunday, 24 April 2016

How to write to file in Java ?


Example
Using FileOutputStream

File file = new File("newfile.txt");
String content = "This is the text content";

// if file doesn't exists, then create it
if(! file.exists()) {
   file.createNewFile();
}

FileOutputStream fop = new FileOutputStream(file);

// Get the content in bytes
fop.write(content.getBytes());
fop.flush();

fop.close();


Example
Using BufferedWriter

FileWriter fw = new FileWriter(file.getName());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);

bw.close();

No comments:

Post a Comment

Note: only a member of this blog may post a comment.