If you only need your numbers in a data structure, e.g. a flat array, then you can read the file with a Scanner
and a simple loop. Scanner
uses whitespace as the default delimiter, skipping multiple whitespaces.
Given List ints
:
Scanner scan = new Scanner(file); // or pass an InputStream, String
while (scan.hasNext())
{
ints.add(scan.nextInt());
// ...
You'll need to handle exceptions on Scanner.nextInt
.
But your proposed output data structure uses multiple arrays, one per line. You can read the file using Scanner.nextLine()
to get individual lines as String
. Then use String.split
to split around whitespaces with a regex:
Scanner scan = new Scanner(file); // or InputStream
String line;
String[] strs;
while (scan.hasNextLine())
{
line = scan.nextLine();
// trim so that we get rid of leading whitespace, which will end
// up in strs as an empty string
strs = line.trim().split("\\s+");
// convert strs to ints
}
You could also use a second Scanner
to tokenize each individual line in an inner loop. Scanner
will discard any leading whitespace for you, so you can leave off the trim
.