Jump to content
  • Advertisement
Sign in to follow this  
41ph4_r4p70r

[java] Reading doubles/integers

This topic is 5457 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
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 );
...

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!