reading integers from text file

Y

yasmine

Hi - newbie programmer...

I have a text file that has numbers seperated by Tabs or Returns. I
want to read these numbers into an array.

I'm using BufferedReader, and when i read one character with
c=in.read(), then print out c, it shows a completely different number.
Using Strings readLine() will print out the integers from the file,
but i want to access each integer separatelyand put them in an Int
array...

I realise its something to do with ASCII, but I don't know and can't
find any diferent reading functions that will print out the number as
it is. I thought read() should read one character at a time?

can anone please help?
 
S

Sudsy

yasmine said:
Hi - newbie programmer...

I have a text file that has numbers seperated by Tabs or Returns. I
want to read these numbers into an array.

Read a line at a time and use a StringTokenizer. Something like this:

BufferedReader br = new BufferedReader( new FileReader( "filename" ) );
String lineIn = null;
StringTokenizer st = null;
String token = null;
while( ( lineIn = br.readLine() ) != null ) {
st = new StringTokenizer( lineIn, " \t\r" );
while( st.hasMoreTokens() ) {
token = st.nextToken();
// do something with the token, like pass
// it to Integer.parseInt
}
}
 
S

Shripathi Kamath

yasmine said:
Hi - newbie programmer...

I have a text file that has numbers seperated by Tabs or Returns. I
want to read these numbers into an array.

I'm using BufferedReader, and when i read one character with
c=in.read(), then print out c, it shows a completely different number.
Using Strings readLine() will print out the integers from the file,
but i want to access each integer separatelyand put them in an Int
array...

I realise its something to do with ASCII, but I don't know and can't
find any diferent reading functions that will print out the number as
it is. I thought read() should read one character at a time?

can anone please help?


Have you considered the use of the StreamTokenizer class?

If not, try it:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/StreamTokenizer.html

HTH,
 
K

Kevin Henry

I usually will get numbers from a text file by doing a readLine() to get a
line then parse it with a StringTokenizer. Then with the tokens you can run
a Integer.parseInt() to get the int.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top