User Program Communication
Write to File in Java
Used to create and write characters to a file.
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();
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.
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();
Java Docs - FileWriter
Java Docs - BufferedWriter