0
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?

2
  • I am a beginner so please go easy!
    – user104827
    Commented Nov 27, 2013 at 22:59
  • 1
    A ballpark estimation of the difference between Programmers.SE and StackOverflow is if you are in front of a whiteboard or an IDE when dealing with the problem. If you are looking at a whiteboard (trying to figure out the algorithm, the design patterns, etc...) then its likely best on P.SE. If it is in an IDE, its probably best on StackOverflow. Your previous question was migrated (automatically moved) to SO and this one is on its way too (please don't repost). For implementation questions (such as this), SO will likely give you an answer much faster than P.SE.
    – user289086
    Commented Nov 28, 2013 at 2:28

3 Answers 3

2

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.

3
  • What about using while and if loops? I am unfamiliar with try-finally.
    – user104827
    Commented Nov 28, 2013 at 1:17
  • @user104827 try ... finally ... syntax here is used to close Scanner properly.
    – Engine Bai
    Commented Nov 28, 2013 at 1:26
  • while ( input.hasNext() ) loop each line in file, if you have to filter the input line, you can add if condition in the while.
    – Engine Bai
    Commented Nov 28, 2013 at 1:28
0

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
}
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.