簡體   English   中英

從文本文件中讀取某些double到列表

[英]Reading certain double from text file into a list

我有這段代碼可以將數字(類型為double)從文本文件讀取到列表中。

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

如何將數字逐行添加到列表中?

正如您所說的是雙打,這會將它們轉換為雙打並將其添加到雙打列表中。 這還有一個好處,就是不會將無法解析為double的任何內容添加到列表中,從而可以進行一些數據驗證。

    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!");
    }

您可以將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()方法)。 在示例代碼中,如果發生異常,流不會關閉。

在代碼中,您逐字符讀取輸入char,這就是為什么看到這樣的輸出的原因。 您可以使用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!");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM