簡體   English   中英

在ArrayList對象中存儲文件中的字符串?

[英]Storing String from file in an ArrayList object?

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文件包含字符串),但我完全迷失了。 有什么建議?

您應該逐行讀取文件並將其存儲到列表中。

這是你應該替換你的代碼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

如果您使用的是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
}

你可以用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)

暫無
暫無

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

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