It sounds like you want to read by line then with Scanner.nextLine()
and Scanner.hasNextLine()
. Of course, if you can use Apache Commons then FileUtils.readLines(File, String)
makes it easy to read the file line-by-line. Once you have a line, you can use Scanner(String)
which (per the Javadoc)
Constructs a new Scanner
that produces values scanned from the specified string.
Something like,
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner strScanner = new Scanner(line);
// ...
}
As @JonSkeet pointed out in the comments, you can also split the line
on white-space like
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] arr = line.split("\\s+");
// ...
}
And as @RealSkeptic points out below might also use Files.readAllLines(Path)
. That might give you a full example like
// Get the user's home directory
String home = System.getProperty("user.home");
File f = new File(home, "input.txt");
try {
// Get all of the lines into a List
List<String> lines = Files.readAllLines(f.toPath());
// Get the line count to create an array.
int[][] arr = new int[lines.size()][];
// populate the array.
for (int i = 0; i < lines.size(); i++) {
// split each line on white space
String[] parts = lines.get(i).split("\\s+");
arr[i] = new int[parts.length];
for (int j = 0; j < parts.length; j++) {
// parse each integer.
arr[i][j] = Integer.parseInt(parts[j]);
}
}
// Display the multidimensional array.
System.out.println(Arrays.deepToString(arr));
} catch (IOException e) {
// Display any error.
e.printStackTrace();
}