簡體   English   中英

從文件寫入 ArrayList

[英]Write from file to ArrayList

程序要運行,需要從文件中向arraylist寫入數據,但是循環中如何讓寫入的元素不等於null呢? 也就是說,一旦從文件中讀取所有行,循環就會停止執行

public static void readFromFile(String path, String filename) throws IOException {
    ArrayList<String> ip = new ArrayList<>();
    try {
        File file = new File(path + "\\" + filename);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        ip.add(br.readLine());
        while ((ip.add(br.readLine()) != null)) {
            //writing to a variable
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

ip.add(...)返回一個boolean 這段代碼無法編譯,因為boolean是一個原語,因此永遠不可能是 null。

add移動到循環內:

String line;
while ((line = br.readLine()) != null) {
  ip.add(line);
}

這是閱讀所有行的更好方法:

Files.readAllLines(Paths.get("path_to_file"), StandardCharsets.UTF_8)

暫無
暫無

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

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