0

在 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....只是在控制台中打印它没有必要...有人可以帮助我,给我一些建议吗?提前致谢

4

2 回答 2

1

再次,将大问题分解成小步骤,解决每个步骤。

  1. 阅读第一行。
  2. 解析第一行以获得 2 个数组的大小。
  3. 创建数组。
  4. 循环第一个数组长度时间并填充第一个数组。
  5. 循环第二个数组长度时间并填充第二个数组。
  6. 在 finally 块中关闭 BufferedReader(确保在 try 块之前声明它)。
  7. 显示结果。
于 2013-08-18T00:34:30.690 回答
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块中。

此外,没有必要在链中拥有DataInputStream和。直接绕一圈InputStreamReader就行了。BufferedReaderFileReader

如果所有这些课程都让你有点困惑;请记住Stream,类用于字节级别的读取,而Reader类用于字符级别的读取。所以,这里只需要Readers。

于 2013-08-18T00:37:44.840 回答