According to some other people, there are other classes specifically designed to read lines of text, such as BufferedReader. However, if you need to use RandomAccessFile, you can read lines of text, but you need to programmatically find where 1 line ends and another line begins ...
A simple example would be ...
RandomAccessFile raf = new RandomAccessFile("c:\test.txt","r"); String line = ""; while (raf.available()){ byte b = raf.read(); if (b == '\n'){ // this is the end of the current line, so prepare to read the next line System.out.println("Read line: " + line); line = ""; } else { line += (char)b; } }
This gives the main building block for the reader who is looking for the end of each line.
If you intend to go the way of using RandomAccessFile, you can start with this structure, but you need to know about a few drawbacks and get-ya, such as ... 1. Unix and Windows use different line markers - you need to look for "\ n" , "\ r" and a combination of both of these 2. Reading one byte at a time is very slow - you have to read a block of bytes into the array buffer (for example, an array of bytes [2048]), and then iterate through the array, replenishing the array from RandomAccessFile when you reach the end of the buffer array. 3. If you are dealing with Unicode characters, you need to read and process 2 bytes at a time, not individual bytes.
RandomAccessFile is very powerful, but if you can use something like BufferedReader, then you will probably be much better off using it since it automatically takes care of all these issues.
source share