读取txt并保存到数组中,java

时间:2013-08-18 00:24:54

标签: java bufferedreader

在java中读取文件时遇到一些问题,并将每个元素保存为2个数组。 我的txt是这样的

2,3
5
4
2
3
1

其中第一行是两个数组A = 2和B = 3的长度,然后是每个数组的元素。我不知道如何将它们保存到A和B中并用它们的长度初始化数组。 最后,每个阵列将是A = [5,4] B = [2,3,1]

public static void main(String args[])
      {
        try{
// Open the file that is the first 
// command line parameter

            FileInputStream fstream = new FileInputStream("prova.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
//Read File Line By Line
            while ((strLine = br.readLine()) != " ")   {
                String[] delims = strLine.split(",");
                String m = delims[0];
                String n = delims[1];
                System.out.println("First word: "+m);
                System.out.println("First word: "+n);
            }
//Close the input stream
            in.close();
            }catch (Exception e){//Catch exception if any
                System.err.println("Error: " + e.getMessage());
                }
        }
    }

这就是我所做的..我使用System.out.println ....只是在控制台中打印它没有必要......有人可以帮助我,给我一些建议吗? 提前谢谢

2 个答案:

答案 0 :(得分:1)

再次,将大问题分解为小步骤,解决每一步。

  1. 阅读第一行。
  2. 解析第一行以获得2个数组的大小。
  3. 创建数组。
  4. 循环第一个数组长度时间并填充第一个数组。
  5. 循环第二个数组长度并填充第二个数组。
  6. 关闭finally块中的BufferedReader(确保在try块之前声明它)。
  7. 显示结果。

答案 1 :(得分:0)

将此答案与@ Hovercraft的答案

中列出的步骤相匹配
String strLine = br.readLine(); // step 1

if (strLine != null) {
  String[] delims = strLine.split(","); // step 2

  // step 3
  int[] a = new int[Integer.parseInt(delims[0])];
  int[] b = new int[Integer.parseInt(delims[1])];

  // step 4
  for (int i=0; i < a.length; i++)
    a[i] = Integer.parseInt(br.readLine());

  // step 5
  for (int i=0; i < b.length; i++)
    b[i] = Integer.parseInt(br.readLine());

  br.close(); // step 6

  // step 7
  System.out.println(Arrays.toString(a));
  System.out.println(Arrays.toString(b));
}

注意,我打电话给br.close()。使用in.close(),您只关闭内部流,并且BufferedReader仍然打开。但关闭外部包装流会自动关闭所有包装的内部流。请注意,像这样的清理代码应始终位于finally块中。

此外,链中不需要DataInputStreamInputStreamReader。只需将BufferedReader直接包裹在FileReader

如果所有这些课程让你有点困惑;只记得Stream类用于在字节级读取,Reader类用于在字符级读取。所以,你在这里只需要Reader

相关问题