RandomAccessFile raf = new RandomAccessFile("things.txt", "r");
raf.seek(0); // Move the file pointer to the beginning
System.out.println("The first number is " + raf.readLine());
// tHIS HOWEVER BRING the entire line while I only want a word
3 Replies - 1246 Views - Last Post: 08 February 2012 - 11:57 AM
#1
Reading one word at a time usinf random access file
Posted 08 February 2012 - 06:20 AM
Hello, I am trying to read one word at a tine using random access file. My file that I am reading from is separated by spaces. RandomAccessFile does not have a method which reads a word. It has readLine(). Do i have to use stringTokenizer to read each word ?
Replies To: Reading one word at a time usinf random access file
#2
Re: Reading one word at a time usinf random access file
Posted 08 February 2012 - 06:59 AM
Well, as said you could read the line and tokenize it (though I think .split() is preferred, I'm not certain)
Or you can just read a byte while(byte is not a space)
Or you can just read a byte while(byte is not a space)
#3
Re: Reading one word at a time usinf random access file
Posted 08 February 2012 - 11:23 AM
Let me be more specific:
I have text file like this:
america mexico canada
china india australia
brazil chile russia
I want to use thr random excess file to read up to the word india and store the words in an array. Then start reading from australia
up to the end and store in another array.
Here's my code:
What i need help on is how to read up to the word india using seek method. I tried to find the entire length of the file and divided it by two so that I can read up the middle, but it seems not to be working
I have text file like this:
america mexico canada
china india australia
brazil chile russia
I want to use thr random excess file to read up to the word india and store the words in an array. Then start reading from australia
up to the end and store in another array.
Here's my code:
raf.seek(0);
System.out.println("The second number is " + raf.readLine());
StringTokenizer tokens;
tokens = new StringTokenizer(line);
int i = 0;
long start = raf.length()/2;
while (line != null && i < start)
{
while(tokens.hasMoreTokens())
System.out.println(tokens.nextToken());
line = raf.readLine();
tokens = new StringTokenizer(line);
i++;
}
What i need help on is how to read up to the word india using seek method. I tried to find the entire length of the file and divided it by two so that I can read up the middle, but it seems not to be working
#4
Re: Reading one word at a time usinf random access file
Posted 08 February 2012 - 11:57 AM
Quote
I want to use thr random excess file to read up to the word india
As you say yourself, raf is not designed to read words. It's not really designed to read lines either - readLine, if not deprecated, it's certainly discouraged.
It would be much better to use Scanner.next
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|