0

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

}
3
  • 2
    What does your code do now? how is it different than expected? Commented Jan 17, 2017 at 16:45
  • I don't think im reading in a text file at all. When I run the program, it gives me the "Give me a file!" prompt, which i have set up Commented Jan 17, 2017 at 16:48
  • How are you trying to read a file? Commented Jan 17, 2017 at 16:49

2 Answers 2

1

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)!

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

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.