Link to home
Start Free TrialLog in
Avatar of cokeman_
cokeman_

asked on

reading doubles from a file

How would I go about reading doubles from a file? Suppose the following as a sample file:

5 4
0.30 0.20 0.10 0.40
0.05 0.15 0.25 0.55
0.30 0.20 0.10 0.40
0.05 0.15 0.25 0.55
0.30 0.20 0.10 0.40

The first line would have two integers -- how many lines there are, and how many doubles were in each line.
Then there would be the specified number of lines and each would have the specified number of doubles (each double would be separated from the other by a space or tab).  

I would like to read the first line into two integer variables, and then the rest of the file into an array (or a vector, but only if it's a must) whose size is determined by the given values.

Thanks
Avatar of cokeman_
cokeman_

ASKER

actually, change that -- it doesn't have to be doubles that are read in -- integers are fine too
You could read eachline in as a string, then use a string tokenizer to get at each value which can be converted to doubles or ints or whatever through methods in each class (Integer, Double, etc)

I have code somewhere to do most of this if you're interested
that would be good.  if possible, could you give me the code to read the lines too? I'm new to file handling in Java and personally, I think it seems to be a pain in the butt =)
You might also want to look at DataInputStream to avoid the use of tokenizers. Additionaly, the use of DataInputStream could be built ontop of a BufferedInputStream to increase performance if you are using large files.
ASKER CERTIFIED SOLUTION
Avatar of dufort
dufort

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Comments:
-it should work well with space, newline and TAB separators
-If the file contains your matrix and some other stuff before and after, you will have to read it - and tokenize it - line by line.
-file handling in JDK1.1.x is very scattered and confusing. I guess the use of BufferedReader and ReadUTF() could enable you to read a file line by line and do the job right.

Have fun!

In the "catch()" part, you should add "output = null;" to help your program detect when there has been input errors.

I think that's all.

on a side note, would you be able to tell me how to concatenate a double to a string? ie, if I were to have a string str and I wanted to do something like
     str = str.concat(doubleNumber);
I believe this can be done with:

str = str.concat((new Double(doubleNumber)).toString());