• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading strings from file  RSS feed

 
Naveen Gabrani
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am writing a small file processing application. It reads a file consisting of a set of lines each of which have the same format - say a string followed by a number followed by a boolean (for example "this is a string" 123 true).
How can I process the file such that I get the String, int, boolean one after the other. I tried to use DataInputStream class and getLine method, but it returns the whole line. The class has methods to read primitive types but not String. Other File classes have read method, but that returns one byte at a time.
Thanks,
Naveen
 
ricky gonzalez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you have a space of "fixed separator" between the different values?
 
Naveen Gabrani
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes the file would have a space or tab as a seperator.
 
Jayakumar Thirumalai
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about using RandomAccessFile (readLine) and StringTokenizer (hasMoreTokens and nextToken).
RandomAccessFile raf = new RandomAccessFile("filename", "r");
String line = raf.readLine();
StringTokenizer st = new StringTokenizer(line);
String s = st.nextToken();
You may use parse to get int from string.
Code the above in appropriate loop.
check for null for end of file.
use st.hasMoreTokens to check the end of st.
Jayakumar
 
Nilesh Srivastava
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

But what if you encountered a null while traversing the StringTokenizer.
It wont take null as Token and thus cud mislead you.

I am facing the similiar problem.
Suppose I have one String as
WORK<tab as separator>HOME<tab as separator><tab as separator>OFFICE.

Now If I run my StringTokenizer on this String it will only return me three Tokens WORK,HOME,OFFICE.

If I wud have to insert the above tab separated String in DB, my fourth token will get inserted in third column and Last column will get Null

Please help on this issue..
Thanks ain Advance
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!