User Program Communication

Write to File in Java

Used to create and write characters to a file.


Syntax
import java.io*;

//create a new File object
File fileObject = new File(filenamePath);
fileObject.createNewFile(); //in case the file does not exist
//create a FileWriter object
FileWriter fw = new FileWriter(fileObject);

//characters or strings to write
fw.write(contentToWrite);

fw.close();

Notes

There are other classes that can be used to write to a file, including BufferedWriter, and OutputStreamWriter. These are used to write other character sets to files.

In order to prevent a memory leak, the writer must be closed.


Example
import java.io*;

File file = new File("marks.txt");

FileWriter fw = new FileWriter(file);

//characters or strings to write
fw.write("80 85 88 75 70");

fw.close();

< Read from Text File   |   Import Package >

© 2018 SyntaxDB. All Rights Reserved.