如果您只需要数据结构中的数字,例如平面数组,那么您可以使用Scanner一个简单的循环读取文件。Scanner使用空格作为默认分隔符,跳过多个空格。
给定List ints:
Scanner scan = new Scanner(file); // or pass an InputStream, String
while (scan.hasNext())
{
ints.add(scan.nextInt());
// ...
您需要处理Scanner.nextInt.
但是您建议的输出数据结构使用多个数组,每行一个。您可以使用来读取文件Scanner.nextLine()以获取单独的行作为String. 然后使用String.split正则表达式拆分空格:
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
}
您还可以使用一秒钟Scanner来标记内部循环中的每一行。Scanner将为您丢弃任何前导空格,因此您可以省略trim.