簡體   English   中英

將字符串文件添加到arraylist

[英]Add a file of strings into an arraylist

我正在嘗試將此文件添加到arraylist中,稍后將與另一個arraylist進行比較。 到目前為止,我已經有了這個,但是它給了我一個編譯錯誤。 據說它找不到符號.hasNext和。 readLine。

ArrayList<String> america = new ArrayList<String>();
    while((infile2.hasNext()))
    {
        america.add(infile2.nextLine());
    }

有人可以幫我弄清楚如何解決這些錯誤嗎?

這是一種可行的方法。

import java.util.Scanner;

Scanner inFile2 = new Scanner(new File("INPUT_FILE_NAME"));

然后,將循環更改為使用hasNextLine()而不是hasNext() 對於Java的Scanner您應始終將has與相應的next類型配對。

您可以別人交給您的BufferedReader 包裹在Scanner中。

 Scanner inFile = new Scanner(myBufferedReader);

是的,它是一個bufferedReader

BufferedReader沒有hasNext方法,因此可以使用readLine

String line;
while((line = infile2.readLine()) != null) {
    americaList.add(line);
}
...

或者如果您可以使用Files

List<String> americaList = 
         Files.readAllLines(Paths.get("list.txt"), StandardCharsets.UTF_8);
       /**
 * one time read all
 * 
 * @param location
 * @return
 */
public static List<String> readLine(String location){
    BufferedReader is = null;
    List<String> result = new ArrayList<String>();
    try {
        is = new BufferedReader(new FileReader(new File(location))); 
        String line = null;
        while((line = is.readLine())!=null){
            result.add(line);
        }
    } catch (FileNotFoundException e) {
        throw Exceptions.unchecked(e);
    } catch (IOException e) {
        throw Exceptions.unchecked(e);
    } finally{
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw Exceptions.unchecked(e);
            }
        }
    }

    return result;
}

暫無
暫無

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

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