This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Im trying to make a program using io that will read 5 records from a text file. They are in the format of name, age, sex, and gpa ex=John Doe 25 M 3.2 I have to write a method that will display all five on the screen. I can do that the first part of my code works. Then I have to use indexOf and get the gpa's out and then insert them into another file I create. That is what I am having trouble on. My code is below. import javax.swing.*; import java.io.*; class HW_4_Code2 { public static void main (String[] args) throws IOException { //setup file and stream File inFile = new File("C:\\hw4\\rawData.txt"); FileInputStream inStream = new FileInputStream(inFile); //set up an array to read data in int fileSize = (int)inFile.length(); byte[] byteArray = new byte[fileSize]; //read data in and display them inStream.read(byteArray); for (int i = 0; i < fileSize; i++) { System.out.print((char)byteArray[i]); } inStream.close();
String last = inFile.substring(inFile.indexOf(" ")+1, inFile.length()); System.out.println(+last); } }
First off, you're going to run into more difficulty because you have no logical field separators. John Doe 25 M 3.2 (How is a program supposed to "know" what part of that is the age, for example? Are all names firstName(space)lastName? What about: John Q. Doe 25 M 3.2) So you need to organize the data with separators, such as: John Doe<t>25<t>M<t>3.2 (where <t> represents the TAB character) Some folks will argue to just use the comma (,) as a separator - but that's inherantly bad, as the fields may have commas embedded within them, making it impossible to tell which commas are data versus separators.
Stephen Barrow
Greenhorn
Joined: Mar 03, 2004
Posts: 13
posted
0
Ok, So we need separators. No problem, but can you point me in the right direction on how to do the rest?
Billybob Marshall
Ranch Hand
Joined: Jan 27, 2004
Posts: 202
posted
0
Stephen Barrow
Greenhorn
Joined: Mar 03, 2004
Posts: 13
posted
0
Is this suppose to replace my existing code?
Billybob Marshall
Ranch Hand
Joined: Jan 27, 2004
Posts: 202
posted
0
Originally posted by Stephen Barrow: Is this suppose to replace my existing code?
Take the ideas within, and incorporate them however you wish.