Java 如何使用扫描仪从文本文件中检测行尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18068756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:10:11  来源:igfitidea点击:

How to detect end of line with Scanner from text file

javaarraysfileinputline

提问by TrMako

So I'm reading an input text file that is 4 lines of single-space separated numbers. The text file is just:

所以我正在阅读一个输入文本文件,它是 4 行单空格分隔的数字。文本文件只是:

5 
9 6
4 6 8
0 7 1 5

I'd like to input these numbers into a 2D array called rows. So for example, rows[1][0]should be 9, the first number in the second row.

我想将这些数字输入到称为行的二维数组中。例如,rows[1][0]应该是9,第二行中的第一个数字。

My problem is when I use the Scanner for in.next()or in.nextInt(), it ignores the end of the line and just keeps on going, so rows[0][1]ends up being 9instead of 0. I'd like for the array to finish populating with 0's if there is no number for that slot. So since the first row is only 1number, 5, I'd like for the array rows[0][0]to be 5, but rows[0][1]to rows[0][3]to be 0.

我的问题是当我将 Scanner 用于in.next()or 时in.nextInt(),它会忽略行尾并继续前进,因此rows[0][1]最终成为9而不是0. 0如果该插槽没有编号,我希望数组以's完成填充。如此以来,第一行是唯一的1号码,5我想为阵rows[0][0]5,但rows[0][1]rows[0][3]0

I've tried using a try/catch for NoSuchElementExceptionand an if in.hasNextLine()but neither of those seemed to work.

我试过使用 try/catch forNoSuchElementException和 if ,in.hasNextLine()但这些似乎都不起作用。

Any ideas or help would be greatly appreciated.

任何想法或帮助将不胜感激。

回答by Hovercraft Full Of Eels

Use more than one Scanner. One Scanner gets each line with nextLine(), and then you feed the line obtained to the next Scanner analyzes each line's tokens. Just be sure to close() of the inner Scanner (and the outer one too) when done using it.

使用多个扫描仪。一个 Scanner 用 获取每一行nextLine(),然后将获得的行提供给下一个 Scanner 分析每行的标记。使用完后,请务必关闭内部扫描器(以及外部扫描器)的 close() 。

Pseudocode:

伪代码:

create fileScanner with file
while fileScanner has more lines
  get next line from fileScanner
  create new Scanner with next line, lineScanner
  while lineScanner has next, 
    get next token.
    do what you want with token.
  close of lineScanner
close fileScanner

回答by Jason C

You can use a Scanner to read individual tokens, and you can use a Scanner to read an entire line, but you cannot use a Scanner to do both.

您可以使用 Scanner 读取单个标记,也可以使用 Scanner 读取整行,但不能同时使用 Scanner 执行两者。

What you want to do is first read the line into a String, then use a Scanner on that String to parse that line, e.g.:

您想要做的是首先将该行读入一个字符串,然后在该字符串上使用扫描仪来解析该行,例如:

BufferedReader lineReader = new BufferedReader(...);
String line;

while ((line = lineReader.readLine()) != null) {
    Scanner scanner = new Scanner(line); 
    // use scanner here
}

You can also use a Scanner to read lines instead of a BufferedReader, but unless you have a specific requirement (e.g. you're trying to drop this into code that already uses a Scanner), it doesn't really matter how you read the lines.

您也可以使用 Scanner 而不是 BufferedReader 来读取行,但除非您有特定要求(例如,您试图将其放入已经使用 Scanner 的代码中),否则您如何读取行并不重要.

Hope that helps.

希望有帮助。

回答by bas

Scanner scanner = new Scanner(
            "5\n9 6\n4 6 8\n0 7 1 5");

while (scanner.hasNextLine())
{
    String currentline = scanner.nextLine();

    String[] items = currentline.split(" ");
    int[] intitems = new int[items.length];

    for (int i = 0; i < items.length; i++)
    {
        intitem[i] = Integer.parseInt(items[i]);
    }
}

回答by Boris the Spider

You should probably use a BufferedReaderand split. The advantage of this is that you know how big to make your arrays in the second dimension as the splitmethod will return an array and you can check its length:

您可能应该使用 aBufferedReadersplit。这样做的好处是您知道在第二维中创建数组有多大,因为该split方法将返回一个数组,您可以检查它的length

public static void main(String[] args) throws Exception {
    final String s = "5\n"
            + "9 6\n"
            + "4 6 8\n"
            + "0 7 1 5";
    final InputStream is = new ByteArrayInputStream(s.getBytes());
    final int[][] array = new int[4][];
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        String line;
        for (int i = 0; (line = br.readLine()) != null; ++i) {
            final String[] tokens = line.split("\s");
            final int[] parsed = new int[tokens.length];
            for (int j = 0; j < tokens.length; ++j) {
                parsed[j] = Integer.parseInt(tokens[j]);
            }
            array[i] = parsed;
        }
    }
    System.out.println(Arrays.deepToString(array));
}

Output:

输出:

[[5], [9, 6], [4, 6, 8], [0, 7, 1, 5]]

As arrays don't expand it's not easy to use them in whileloops that you don't know the size of. Using splitallows you to simply do final int[] parsed = new int[tokens.length];which with a Scannerover whitespace you could not do.

由于数组不会扩展,因此在while您不知道其大小的循环中使用它们并不容易。使用split让您只需做final int[] parsed = new int[tokens.length];它用Scanner了空白,你不能这样做。

The first dimension size is hard coded however as said your file always has 4 lines.

第一维大小是硬编码的,但是正如所说您的文件总是有 4 行。

回答by hamed jaffari

At the endof each line, there is '\n',and at the firstof each line(except first line), there is '\r'. You can control your file by them.

在每一行的末尾,有'\n',在每行的第一行(除了第一行),有'\r'。您可以通过他们控制您的文件。