简体   繁体   中英

Reading from text file and storing contents in separate arrays

I have a text file containing

r0, 0.5, 1
r1, 0.6, -1
r2, 0.2, 1

I want read the file and store each column in a separate array in java. This is the code I have been writing. I am only getting garbage values in the records. Also, I am not able read the float values. Please tell me how to fix this.

public class Model{
    private String modelname ;
private String[] records ;
private int[] targets ;
private float[] scores ;

    public Model(String name_model, String path) throws NumberFormatException, IOException {


    this.modelname = path+name_model ;
    System.out.println(this.modelname);

    BufferedReader bufferReader = new BufferedReader(new FileReader(path+name_model));
    String line=null;
    int t=0;
    while((line = bufferReader.readLine())!=null) {
        System.out.println(line);
        //String[] strar = line.split(",");
        //String[] strar = line.split("\\s*,\\s*")  ;
        int k=1 ;
        for(String part : line.split(",")) {
            if (k==1) {
                System.out.println(part.trim());
                this.records[t] = part.trim() ;
                            }
            if (k==3)
                this.targets[t] = Integer.valueOf(part.trim()) ;
            if (k==2)
                this.scores[t] = Float.parseFloat(part.trim()) ;
            k=k+1 ;
        }
        System.out.println(this.records[t] + " " + this.targets[t] + " " + this.scores[t]);
        t=t+1;
    }
}
public static void main(String[] args) throws Exception, IOException {

    String s1, s2, s3 ;
    s1 = "./direc/" ;
    s2 = "file1.txt" ;
    s3 = s1+s2 ;
    System.out.println(s3);
    new Model(s2, s1);
}

}

If you don't use braces in the if (k==1) case, this.records[t] gets assigned the last part always. The code should be:

        if (k==1) {
            System.out.println(part.trim());
            this.records[t] = part.trim() ;
        }

Also, you're missing a comma after the 0.6 on the second line of input.

You can simplify the parsing. You can do away with the inner loop and avoid trimming as

String[] parts = line.split(", ");

this.records[t] = parts[0];
this.scores[t] = Float.parseFloat(parts[1]);
this.targets[t] = Integer.parseInt(parts[2]);

I'm assuming you forgot to put the second comma here

r1, 0.6, -1

And, since you're using a primitive int[] use Integer.parseInt() instead of Integer.valueOf() (which returns an Integer wrapper) to avoid unnecessary unboxing.

EDIT :
You also need to initialize all of your Arrays like

private String[] records = new String[100]; // initialization is MISSING!

Since, in your case the size of the Array depends on the number of lines in your input data file it needs to be dynamic. Consider switching to an ArrayList that would grow dynamically.

private List<String> records = new ArrayList<String>();
private List<Integer> targets = new ArrayList<Integer>();
private List<Float> scores = new ArrayList<Float>();

Since, you need to use the wrapper types to be able to use collections; switch back to valueOf() methods.

String[] parts = line.split(", ");

this.records.add(parts[0]);
this.scores.add(Float.valueOf(parts[1]));
this.targets.add(Integer.valueOf(parts[2]));

A simple way i like to use for reading files would be utilising the Scanner and File classes

so start by importing those java.util.Scanner; java.io.*;

then in your code (don't forget to throw IOException): File filename = new File("filename.txt"); Scanner fileScanner = new Scanner(filename);

now if your using arrays, you need to know the size of the array in order to create it, and its type.

and considering your text file looks like this:
1.0 2.7 6.3 8.4 8.6
2.0 9.4 9.1 3.0 4.2
3.4 7.7 8.3 3.2 1.0

if your file can contain comma's add this line after creating your scanner:

fileScanner.useDelimiter(", ")

and you would like 5 arrays containing each row of floats or integers etc... create 5 arrays with the size (here 3), then use this loop to add each number:

int rank = 0;
double[] r1 = new double[3];
.
.
.
double[] r5 = new double[3];
while(fileScanner.hasNext())
{
    if(fileScanner.hasNextDouble()) r1[rank] = fileScanner.nextDouble();
    if(fileScanner.hasNextDouble()) r2[rank] = fileScanner.nextDouble();
    if(fileScanner.hasNextDouble()) r3[rank] = fileScanner.nextDouble();
    if(fileScanner.hasNextDouble()) r4[rank] = fileScanner.nextDouble();
    if(fileScanner.hasNextDouble()) r5[rank] = fileScanner.nextDouble();
    rank++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM