Reputation: 31
In Java I'm using the Scanner
to read from a text file,
for example (cat, dog, mouse).
When I use the System.out.println()
the output appears like cat, dog, mouse
I want the list to look like this
cat
dog
mouse
any help code below
Scanner scan = null;
Scanner scan2 = null;
boolean same = true;
try {
scan = new Scanner(new
File("//home//mearts//keywords.txt"));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
List<String> firstLines = new ArrayList<String>();
while (scan.hasNextLine()) {
firstLines.add(scan.nextLine());
System.out.println(firstLines);
}
Upvotes: 1
Views: 84
Reputation: 23352
Try something like:
firstLines.forEach(System.out::println);
By the way, as you are only reading lines, you may also want to have a look at java.nio.file.Files:
Path keywordsFilepath = Paths.get(/* your path */...);
Files.lines(keywordsFilepath)
.forEach(System.out::println);
Upvotes: 2
Reputation: 312259
You are reading the file line by line, instead of taking the delimiters into consideration:
try (Scanner scan =
new Scanner("//home//mearts//keywords.txt").useDelimiter(", ")) {
while (scan.hasNext()) {
System.out.println(scan.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace(); // Or something more useful
}
Upvotes: 2