Re: RandomAccessFile Seek (find CR)



Yogi_Bear_79 wrote:
"Roedy Green" <my_email_is_posted_on_my_website@xxxxxxxxxxxxxx> wrote in message news:4kln025aq1ompadg20c6tl2bnvg8pg0elb@xxxxxxxxxx
On Sun, 5 Mar 2006 22:16:51 -0500, "Yogi_Bear_79" <nospam@xxxxxxxxxxx>
wrote, quoted or indirectly quoted someone who said :

I am using RandomAccessFile. When I select a random seek point in the file,
I want to move the seek point to the begining of that respective line. So
that the entire line is printed to console.
how is your file encoded? RandomAccessFile is not suited to variable
length encodings like UTF-8. You would want to prepare a file of pure
16 bit chars, for example to be able to index without complication.

If you have 8-bit encodings, you must read bytes then convert to char.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.


This is 8-bit. A imple .txt file from notepad. I understadn there probbaly isn't a real world app for waht I am doing, butthis is just a stand alone example. How would I read the bytes and convert to charand test for CR? I have the rest of the code worked out just need a little help please.



Yogi:

We tried to explain to you that this is the wrong tool for the job. You could make your data into fixed length records and you wouldn't need to know anything about the CR or you can use a Reader to read lines of text out of your text file.

But since you really don't want to know how to do the job correctly I'll show you how to do it the wrong way.

First note that Notepad doesn't just put a CR at the end of the line it puts a LF too.

This is pseudo code, you will need to actually write your own code with all of the Exception handling and missing bits.

open the random access file
seek to starting point
int n = 0;
// while the character isn't a linefeed
while ((n = file.read()) != 0x0a) {
// get the file pointer
long pos = file.getFilePointer();
// seek to byte before last read byte
file.seek(pos-2);
}
// n is now the first character of your line
char[] chars = new char[??];
chars[0] = n;
int i=1;
// while it isn't a carriage return
while ((n = file.read()) != 0x0d)
char[i++] = n;
// when the while above is done your array has i characters in it
String str = new String(chars,0,i);
close the file

This is really MM. I don't know what value it is to learn something that should never be used in actual work.

--

Knute Johnson
email s/nospam/knute/
.


Quantcast