Results 1 to 3 of 3
Thread: Help with filereader in java
- 07-24-2007, 04:14 AM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
Help with filereader in java
I'm writing a program now that takes a ID and 3 numbers fom a text file each in a line such as "23AFS 98 34.3 99" on each line, seperated by a space each. Im using a scanner and filereader to get the information from the file but Im not sure as to how I can set these numbers so that I can get the average, min value, max value etc.
Here is the code for the filereader.
If anymore information is needed, just ask. Mainly I just need to set it up as each ID in a variable and each number in a variable, I think thats what I have to do but I can't figure it out exactly, and is this the best way to do it? Thanks.Java Code:try { FileReader reader = new FileReader("scores.txt"); Scanner in = new Scanner(reader); while (in.hasNext()) { String line = in.next(); } } catch (IOException exception) { System.out.println("Error procession file: " + exception); }
- 07-25-2007, 11:06 PM #2
Member
- Join Date
- Jul 2007
- Posts
- 55
- Rep Power
- 0
take the contents of the line and load it into a stringtokenizer. Iterate through the stringtokenizer and pull the values out.
- 07-26-2007, 09:55 AM #3
Member
- Join Date
- Jul 2007
- Location
- England, Bath
- Posts
- 47
- Rep Power
- 0
Here this is an example of what you need to do:
Beware though I have not tested this code or compiled it so treat it thus.Java Code:BufferedReader reader = null; try { //Generate a file reader to read the file FileReader fileReader = new FileReader("YourFile.txt"); //Use a BufferedReader to allow each line to be read one at a time. reader = new BufferedReader(fileReader); String line = null; //Load the next line and check the results were not null Note the ()'s while(null != (line = reader.readLine())) { //Take advantage of the split method to split each item out. String[] items = line.split(" "); String idString = items[0]; long id = Long.parseLong(idString); //Repeat with other numbers using the wrapper objects parse methods. } } catch(Exception e) { //TODO Implement proper error handling. e.printStackTrace(); } finally { try { reader.close(); } catch(Exception e) { e.printStackTrace(); } }
Hopefully its pretty self explainatory but if you need a bit more help let me know.Last edited by shanePreater; 07-26-2007 at 09:57 AM. Reason: Missed the finally!
Similar Threads
-
FileReader Vs FileInputStream and same goes to output
By unhurt in forum New To JavaReplies: 5Last Post: 02-02-2010, 09:06 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks