[java] Reading doubles/integers

Started by
2 comments, last by CaptainJester 19 years, 6 months ago
I have a text file with a bunch of numbers (most are doubles), likely, I know the first line says the number of objects p and then a lot of numbers for every p (from i=1 to p). Well this doesnt matter , my question is, whats the most recommended class I should use in order to read Integers or Doubles, something like reader.readInt() or like that. So far Ive been using a buffered reader, then I use readLine() and split() to cut the read string into small ones that contain each number, suppose the first line in the file reads : _15_40_ (where _ = whitespace) then I do String s=reader.readLine(); s.trim(); //eat the whitespaces String []new=s.split(" "); (and then new would be an array of 2 strings "15" and "40") and something like that for the rest of the file, I was just wondering if theres a more optimized way to do this with a class that implements reading Integers or Doubles (and is aware of whitespaces) or I should just continue the way Im doing it thx
Advertisement
well, if you're only reading numbers, you can investigate class BaseFileIO. it seems to have the methods you require.
hope that helped. also, RandomAccessFile appears to have them as well.
- stormrunner
StringTokenizer, StreamTokenizer, are two quite different approaches which can take a lot of the pain away.

Beyond that, if your file format is more complex you might want to use regular expressions (java.util.regex).

If your file format is only ever numbers, the *easiest* way to do it is usually:

BufferedReader r = new BufferedReader( new InputStreamReader( new FileInputStream( f ) ) );
...
String line = r.readLine();
int i = Integer.parseInt( line );
...
You want to use DataInputStream if it is a binary file. It reads data exactly like you want. ie readDouble, readInt, etc.

If it is a text file, then StreamTokenizer would be the best option. (As the AP said.)
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][LWJGL Tutorials for NeHe][LWJGL Wiki][jMonkey Engine]

This topic is closed to new replies.

Advertisement