Java Reference
In-Depth Information
write(str,start,length) writes the number of characters equivalent to the
current value of length of string str starting at position start of the string.
The text is appended to the previously written text.
10.1.3
Dealing with text files
The program FileReadWrite is given below and demonstrates the methods de-
scribed above. It reads some characters from the file testtext1.txt and stores
them in a buffer ( char -array) for potential further use. The buffer is initialized
with dashes ( - ), so that the unused parts are visible when it is printed. The buffer
is written to the standard output (screen). After this, a part of the buffer is written
to another file testtext2.txt .Ifthis file already exists, it is first erased. The
!
constant path has to be changed if the directory structure is different from the
one in the downloaded files. The path name has to end with a slash ( / )ortwo
backslashes. Below we list the content of file testtext1.txt on the left and that
of testtext2.txt on the right:
Line 1
ne 1
Line 2
Line 2
Line 3
Line 3
Line 4
Line 4
Line 5
Line
Line 6
Line 7
Line 8
Line 9
The last line
When the buffer is printed, one can see that the line breaks appear as in the file
because a FileReader reads the line break characters ( \ n ).
File: its/TextIO/FileReadWrite.java
1. package its.TextIO;
2.
3. import java.io.File;
4. import java.io.FileReader;
5. import java.io.FileWriter;
6.
7. public class FileReadWrite
8. {
9. // This variable has to be set according to your system
10. public static String path = "./its/TestData/";
11.
12. public FileReadWrite(String ReadFileName,String WriteFileName)
13. {
Search WWH ::




Custom Search