input file contains the integer 322 (with no spaces before 322) heres my output ---------------- 13106 Press any key to continue... Seems like such a simple thing to read an integer from a text file.. very fustrating
I/O in Java is a little complicated, for sure ... but once you're used to playing with Streams and Writers, you can do powerful stuff relatively easily. DataInputStream reads data in platform-independent binary format. That is, for an int it reads four bytes, and stores those directly as the value of the int to which you read. Rather than this, you want to a human-readable integer. The easiest way to do this is with two steps: 1. Read the String value of the integer from the file. 2. Convert the String version to an integer. The easiest way to read a String from a file is with a BufferedReader attached (ultimately) to a FileInputStream, like this:
Then, use the readLine() method to get the String containing "322". Second, to convert to int, you can use the Integer.parseInt method. Hope this helps. Cheers,
--Tim [ April 19, 2004: Message edited by: Tim West ] [ April 19, 2004: Message edited by: Tim West ]
Thanks Tim that would work but my inout isnt just an integer.. So i dont think it can be read line by line as a string... Would require a lot of parsing if i did it that way... my input file consists of: 5 w 350.00 integer, followed by a char, followed by a float...
Hmm, sounds like you'll have to do a lot of parsing then - I don't know of an easy way to read ints straight off a Stream (or Reader) in human-readable form if you're only using the library classes. As Eddie points out, StringTokenizer will make your life easy with a simple file format like you have. You'll have to use various methods to convert from String to double, char etc, but each of these is just one method call, provided you know the one to use.