将字符串文件添加到arraylist中

时间:2014-04-16 02:33:25

标签: java arraylist

我试图将此文件添加到arraylist中,稍后我将与另一个arraylist进行比较。到目前为止,我有这个,但它给了我一个编译错误。它说无法找到符号.hasNext和。的readLine。

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

有人可以帮我弄清楚如何解决这些错误吗?

3 个答案:

答案 0 :(得分:1)

这是一种可能的方法。

import java.util.Scanner;

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

然后,将您的循环更改为使用hasNextLine()而不是hasNext()。 对于Java的Scanner,您应始终将has与相应类型的next配对。

您可以打包有人将您带到扫描仪内的BufferedReader

 Scanner inFile = new Scanner(myBufferedReader);

答案 1 :(得分:1)

  

是的,它是一个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);

答案 2 :(得分:0)

       /**
 * 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;
}