简体   繁体   中英

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!");
          }   
    }   
}

I am trying to read a file and add the contents to an arraylist object ( .txt file contains strings), but I am totally lost. Any advice?

You should read the file one line by one line and store it to the list.

Here is the code you should replace your 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();
}

And you should close the Scanner after reading the file.

If you're using Java 7+, then you can use the Files#readAllLines() to do this task for you, instead of you writing a for or a while loop yourself to read the file line-by-line.

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
}

You can do it in one single line with 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM