Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Java file reading and array help?

Name: Anonymous 2011-09-11 23:43

Hello all,

I need to read a data file (specified in command line when launching the program) and load the values from the file into a 2D array.
The data file will be two columns with an undetermined number of rows.

Example
2001     123987
2002     124678
2003     126098
etc.

I'm not quite sure how to define that array (can I analyze the file somehow before creating the array so the program knows how many rows there are?) If not, then I will just set the value of rows to 50.
Since the file has to be specified in the CL at launch, the only way I know to call the file is by using args as an identifier.
like if I have

      for (int i = 0; i < args.length; i++)
        System.out.println("Input file: " + args[i]);

then my program will output "Input file: myfile.data" for "C:\Anon\> Java MyProgram myfile.data"

How could I set up a for loop with the input scanner or something to fill an array with the values from the specified file?

I'm very novice at this, thank you so much for your help!

Name: Anonymous 2011-09-12 2:00


for (int i = 0; i < args.length; i++) {
    File file = new File(args[i]);
    BufferedReader reader = new BufferedReader(new FileReader(file));

    String line = null;
    while ((line = reader.readLine()) != null) {
         // process line
         // insert line to array
    }
}

Name: Anonymous 2011-09-12 11:54

Thank you! I've been trying to get your code to work and learning how to use BufferedReader, FileReader, and LineReader as well as making sure the exceptions are thrown correctly.
This will produce a string array though, correct?
I really need to input the values from the file into my array as integers..

Name: Anonymous 2011-09-12 12:47

you can use Integer.parseInt

also for the unknown array size problem you can make a simple implementation of a one way list

Name: Anonymous 2011-09-12 15:03

GC is shit.

Name: Anonymous 2011-09-12 16:12

>>2

Why don't you use

for (String arg : args) {
  /* etc ... */
}


?

Name: Anonymous 2011-09-12 17:37

>>6
because OP used the ordinary for loop in his post

>>3
int parsedValue = Integer.parseInt(stringValue);

also, look at Lists or ArrayLists, Vectors. These were data structures that can increase it size on the fly.

Name: Anonymous 2011-09-12 17:39

>>4
no need for OP to make his own implementation. Java already has several different implementation of Lists and Collections.

Name: Anonymous 2011-09-12 17:52

>>6
[b]ENTERPRISE QUALITY[/n]

Don't change these.
Name: Email:
Entire Thread Thread List