Java Reference
In-Depth Information
Reading a text file involves instantiating a FileReader . In the following exam-
ple, you'll make use of BufferedReader for its readLine() method. The readLine()
method expects a carriage return, a line feed, or carriage return-line feed pair to in-
dicate the termination of a line.
// Create reader related to a disk file.
FileReader fileReader = new FileReader("myfile.txt");
BufferedReader bufReader = new BufferedReader(fileReader);
// Read a line.
String line = bufReader.readLine();
// Check for end of file when line equals null. If not, print line and
// read another.
while (line != null) {
System.out.println(line);
line = bufReader.readLine();
}
bufReader.close();
fileReader.close();
If you needed to handle differences in character sets, the code would be slightly
more complex. Let's say the file came from China.
// Define the encoding for Chinese.
String encoding = "zh_CN";
// Create streams related to a disk file.
FileInputStream instrm = new FileInputStream("myfile.txt");
InputStreamReader instrmReader = new InputStreamReader (instrm, encoding);
At this point, you could read the file and each line would return a string with
the correct Unicode encoding. Quite likely println() would not be able to display
the correct characters to the console. However, if the machine where the program
was running had support for the Chinese character set, a display of the strings in a
graphical environment would show the Chinese characters correctly.
Writing a text file is just as simple as reading one. As you might expect, for
every Reader there's a Writer .
// Create writers related to a disk file.
FileWriter fileWriter = new FileWriter(("myfile.txt");
BufferedWriter bufWriter = new BufferedWriter(fileWriter);
// Write two lines each, followed by a new line.
bufWriter.write("line one"]);
bufWriter.newLine();
Search WWH ::




Custom Search