Is it possible to position cursor to the start of a specific line in a file through RandomAccessFile?
For e.g. I want to change String starting at char 10 till 20 in
As some other people have stated, there are other classes that are specifically designed to read lines of text, such as BufferedReader. However, if you are required 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 may 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 basic building block for a reader that looks for the end of each line.
If you intend to go down the path of using RandomAccessFile, you can start with this framework, but you need to be aware of a number of drawbacks and got-ya's such as... 1. Unix and Windows use different line markers - you'll need to look for '\n', '\r' and a combination of both of these 2. Reading a single byte at a time is very slow - you should read a block of bytes into an array buffer (eg a byte[2048] array) and then iterate through the array, refilling the array from the 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, rather than single bytes.
RandomAccessFile is very powerful, but if you can use something like BufferedReader then you'd probably be much better to use that instead, as it takes care of all these issues automatically.