How to write into a File in Java?

We can write contents into a file using two methods , using BufferedWriter and FileOutputStream , lets see how we can write the contents using these methods :

Writing a file using BufferedWriter :
BufferedWriter write text to a character-output stream, it buffers characters to provide efficient writing of single characters, Strings and Arrays. We can also pass buffer size if not provided default size is used which is considerably large to perform most of the writing operations.
When writing new line character a new method newLine() is provided, as we can see in below example we are creating a FileWriter object and passing it to the BufferedWriter object and we use write method to write the contents, after writing the contents we are closing the BufferedWriter.


BufferedWriter out = null;
try{
FileWriter fWriter = new FileWriter("C:\\test1.txt"); //Creates new file if already not exists
out = new BufferedWriter(fWriter);
out.write("This is a test");
out.newLine(); // Writes new line

}catch(IOException es){

}finally{

if( out != null){
try{
out.close();
}catch(IOException es){

}
}
}



Writing using FileOutputStream:

FileOutputStream is a stream used to write the contents into a File. But when we write string object we need to convert it to byte and then send it to the write method.


FileOutputStream fopStream = null;
try{
File testFile = new File( "C:\\test7.txt" );
fopStream = new FileOutputStream(testFile);

if(!testFile.exists()){
testFile.createNewFile();
}
String str="This is a test using FileOutputStream";
fopStream.write(str.getBytes());



}catch(IOException es){

}finally{

if( fopStream != null){
try{

fopStream.flush();
fopStream.close(); //Close the output stream
}catch(IOException es){

}
}
}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment