Scanner
The first program uses Scanner class to read the content of a text file and display the output on the screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.util.*; import java.io.*; |
Scanner sc=new Scanner(new FileInputStream("article.txt"));
The constructor takes a FileReader object as a parameter.
sc.hasNext()
Returns true if there is another token (\n) in the input. In this case it will check if there is another paragraph in the text.
sc.nextLine()
This method reads a line of input and advances the cursor in the next line (paragprah).
FileReader
The following code utilizes the combination of FileReader and BufferedReader classes to perform the same task. FileReader is a class which is desiged for reading character files. BufferedReader class makes the reading process easier as it provides a method to read a line of text (readLine).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import java.io.*; |
while(true){ String datarow=br.readLine(); if(datarow==null) break; System.out.println(datarow); }
BufferedReader.readLine() does the job inside a while loop. When no more data is available, readLine returns null and break is executed.
RandomAccessFile
The following program utilizes RandomAccessFile to read a text file. The advantage of using this class is it uses pointer that allows user to easily move to a new point in the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.*; |
raf=new RandomAccessFile(filename,"r");
RandomAccessFile has a number of file access modes. "r" means read only and "rw" means read/write mode.
raf.seek(0);
The pointer is positioned to the beginning of the text file.
while(raf.getFilePointer()<raf.length()){ c=(char)raf.readByte(); System.out.print(c); }
The position of the pointer is compared with the length of the text file (end of file). The reading process will continue as long as the pointer has not reached the end of the file. The content of the text file is fetched character by character.
No comments:
Post a Comment