简体   繁体   中英

How to read inputs from a text file and put those inputs into an ArrayList in Java?

so I want to read in a text file with a bunch of inputs containing strings like this:

abc456
mnjk452
aaliee23345
poitt78

I want to put each of these inputs into an array list and pass that arraylist through one of my methods. How would I go about doing so? Currently in my code, I'm trying to see if i can simply print out what's in my arraylist. Here is what i have in my main:

public static void main(String[] args) {
        if(args.length < 1) {
            System.out.println("Give me a file!");
        }

        String fname = args[0];

        ArrayList<String> coordinates = new ArrayList<String>();

        Scanner grid = new Scanner(fname);
        while(grid.hasNext()) {
            coordinates.add(grid.nextLine());
        }

        for(String coordinate : coordinates) {
            System.out.println(coordinate);
        }

}

How about this:

Path path = Paths.get(args[0]);
List<String> coordinates = Files.readAllLines(path);
System.out.print(coordinates); // [abc456, mnjk452, aaliee23345, poitt78]

Same can be accomplished with the Scanner:

Path path = Paths.get(args[0]);
List<String> result = new ArrayList<>();
Scanner sc = new Scanner(path);
while (sc.hasNextLine()) {
    String line = sc.nextLine();
    result.add(line);
}
System.out.print(result); // [abc456, mnjk452, aaliee23345, poitt78]

Do not forget to pass your arguments when you run your application (either in your IDE or command line)!

When reading from a file you need to create a File object that you give to the Scanner object. Also you should control your while loop based on grid.hasNextLine() since you are grabbing line by line. Lastly when running the program from terminal you should be doing the following

java "name of your class with main" "file name"

Which will pass that file in as a parameter to args[0]

try
{
    Scanner grid = new Scanner(new File(fname));
    while(grid.hasNextLine()) 
    {
        coordinates.add(grid.nextLine());
    }
}catch(FileNotFoundException e)
{
    System.err.println("File " + fname + " does not exist/could not be found");
    e.printStackTrace();
}

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