Java FileWriter Example

The WriteFile example writes ten lines of text to a file, File1.txt.

WriteFile

import java.io.*;

public class WriteFile
{


public static void main(String[] args) throws
IOException
{
String text;
int i;

File outputFile = new File(''File1.txt");
FileWriter out = new FileWriter(outputFile);
for (i=1; i<11; i++)
{
text = "Line " + i + " of text\n";
out.write(text);
}
out.close();
}
}



As the FileWriter write method throws an IOException, we include the clause throws IOException in the main declaration (lines 5–6). Line 10 creates a file object, outputFile, associated with the physical file File1.txt. In line 11, this file object is then passed as an argument to the FileWriter constructor, which creates an output stream, out. We could have omitted creating the file object and passed the file name as an argument to the FileWriter constructor, as follows:

FileWriter out = new FileWriter("File1.txt");

In lines 12–15, we have a for loop that, for each of ten iterations, creates a line of text held in the string variable, text. In line 13, note that the last character in the string is \n; this creates a new line after the string has been output. In line 14, the text is output to the file using the java.io.FileWriter.write method.

Finally, in line 16, we use the java.io.FileWriter.close method to close the output stream and release associated system resources. We do not have to explicitly close the output stream; it is implicitly closed by the Java garbage collector when the output stream object is no longer referenced. However, it is good practice to explicitly close streams when they are no longer needed.

No comments:

Post a Comment