在ArrayList对象中存储文件中的字符串?

时间:2013-11-27 22:58:35

标签: java eclipse

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;


public class Cities {

    public static void main(String[] args) throws IOException {

        String filename;
        System.out.println("Enter the file name : ");
        Scanner kb = new Scanner(System.in);
        filename = kb.next();

        //Check if file exists 
          File f = new File(filename);

          if(f.exists()){

            //Read file
            File myFile = new File(filename);
            Scanner inputFile = new Scanner(myFile);

            //Create arraylist object
            ArrayList<String> list = new ArrayList<String>();

            String cit;

            while(inputFile.hasNext()){
                cit = inputFile.toString();
                list.add(inputFile.toString());
            }
            System.out.println(list);  

          }else{
              System.out.println("File not found!");
          }   
    }   
}

我正在尝试读取文件并将内容添加到arraylist对象(.txt文件包含字符串),但我完全迷失了。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您应该逐行读取文件并将其存储到列表中。

以下是您应该替换while (inputFile.hasNext())的代码:

Scanner input = null;
try
{
    ArrayList<String> list = new ArrayList<String>();
    input = new Scanner( new File("") );
    while ( input.hasNext() )
        list.add( input.nextLine() );
}
finally
{
    if ( input != null )
        input.close();
}

您应该在阅读文件后关闭Scanner

答案 1 :(得分:0)

如果您使用的是Java 7+,那么您可以使用Files#readAllLines()为您执行此任务,而不是自己编写forwhile循环来阅读文件逐行。

File f = new File(filename); // The file from which input is to be read.
ArrayList<String> list = null; // the list into which the lines are to be read
try {
    list = Files.readAllLines(f.toPath(), Charset.defaultCharset());
} catch (IOException e) {
    // Error, do something
}

答案 2 :(得分:0)

你可以用Guava一行完成。

final List<String> lines = Files.readLines(new File("path"), Charsets.UTF8);

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)