【问题标题】:Reading certain double from text file into a list将文本文件中的某些双精度读入列表
【发布时间】:2018-02-05 15:14:06
【问题描述】:

我有这段代码可以将数字(双精度类型)从文本文件读取到列表中。

ArrayList listTest = new ArrayList();
try {
    FileInputStream fis = new FileInputStream(path);
    InputStreamReader isr = new InputStreamReader(fis, "UTF-16");
    int c;
    while ((c = isr.read()) != -1) {
        listTest.add((char) c);
    }
    System.out.println();
    isr.close();
} catch (IOException e) {
    System.out.println("There is IOException!");
}

但是,输出看起来像:

1
1
.
1
4
7

4
2
.
8
1
7
3
5

而不是

    11.147
    42.81735

如何将数字逐行添加到列表中?

【问题讨论】:

    标签: java arrays list file


    【解决方案1】:

    正如您所说的那样,它们是双打,这会将它们转换为双打并将它们添加到双打列表中。这还有一个好处是不会将任何无法解析为双精度的内容添加到您的列表中,从而提供一些数据验证。

        List<Double> listTest = new ArrayList<Double>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"))) {
            String line;
            while ((line = br.readLine()) != null) {
                try {
                    listTest.add(Double.parseDouble(line));
                } catch (NumberFormatException nfe) {
                    // Not a double!
                }               
            }
            System.out.println();
        } catch (IOException e) {
            System.out.println("There is IOException!");
        }
    

    【讨论】:

    【解决方案2】:

    您可以将InputStreamReader 包装在具有readLine() 方法的BufferedReader 中:

    List<String> listTest = new ArrayList<String>();
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-16"))) {
        String line;
        while ((line = br.readLine()) != null) {
            listTest.add(line);
        }
        System.out.println(listTest);
    } catch (IOException e) {
        System.out.println("There is IOException!");
    }
    

    另外,请注意自动关闭流的try-with-resources 语句(如果您使用的是JDK1.6 或更低版本,请在finally 块中调用close() 方法)。在您的示例代码中,如果出现异常,流不会关闭。

    【讨论】:

      【解决方案3】:

      在您的代码中,您逐个字符地读取输入字符,这就是您看到这样一个输出的原因。您可以使用Scanner 以更简洁的方式读取输入文件,而无需与流阅读器等作斗争。

      ArrayList listTest = new ArrayList();
      try {
         Scanner scanner = new Scanner(new File(path));
         while (scanner.hasNext()) {
            listTest.add(scanner.nextLine());
         }
         scanner.close(); 
      } catch (IOException e) {
         System.out.println("There is IOException!");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多