繁体   English   中英

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

[英]Read txt and save into array,java

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

同样,将大问题分解为小步骤,解决每一步。

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

将此答案与@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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