将数据从文件加载到Vector结构

owc*_*wca 6 java parsing file vector

我正在尝试解析固定宽度格式的文件,从中提取x,y值,然后将它们存储在int[]Vector 中的数组中.文本文件如下所示:

0006 0015
0125 0047
0250 0131

那是代码:

    Vector<int[]> vc = new Vector<int[]>();

    try {
        BufferedReader file = new BufferedReader(new FileReader("myfile.txt"));
        String s;
        int[] vec = new int[2];

        while ((s = file.readLine()) != null) {
            vec[0] = Integer.parseInt(s.substring(0, 4).trim());
            vec[1] = Integer.parseInt(s.substring(5, 8).trim());
            vc.add(vec);
        }
        file.close();
    } catch (IOException e) {
    }

    for(int i=0; i<vc.size(); i++){
        for(int j=0; j<2; j++){
            System.out.println(vc.elementAt(i)[j]);
        }
    }
Run Code Online (Sandbox Code Playgroud)

但输出只显示最后一行.

250  
131  
250  
131  
250  
131
Run Code Online (Sandbox Code Playgroud)

我应该以某种方式Vector.nextElement()在这里使用我的所有数据吗?

小智 3

您需要在循环的每次传递中创建一个新的 int[]

    while ((s = file.readLine()) != null) {
        int[] vec = new int[2];
        vec[0] = Integer.parseInt(s.substring(0, 4).trim());
        vec[1] = Integer.parseInt(s.substring(5, 8).trim());
        vc.add(vec);
    }
Run Code Online (Sandbox Code Playgroud)

否则,您只会对同一数组有多个引用,并在每次传递时覆盖该数组。