扫描器与文件输入流

3
Scanner scanner= new Scanner(new File("target.txt"));

并且

FileInputStream d = new FileInputStream("target.txt");

Scanner.nextByte()FileInputStream.read()有什么区别?

我试图理解这个问题,因为当我使用FileInputStream从一个简单文本文件中按字节(逐个)读取时,它可以正常工作。但是当我使用Scanner时,scanner.nextByte()没有返回任何内容。

为什么会这样呢?


你在Scanner上使用了分隔符吗,像scanner.useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next()这样的? - undefined
3个回答

4
Scanner.nextByte()会读取下一个标记,如果它可以作为字节进行评估,则返回该字节,而FileInputStream.read()将返回文件的每个字节。考虑以下示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class SO {
  public static void scanner() throws FileNotFoundException {
    System.out.println("Reading with the Scanner Class:");
    Scanner scanner= new Scanner(new File("target.txt"));
    while(scanner.hasNext()) {
      try {
        System.out.println("A Byte:"+scanner.nextByte());
      } catch(InputMismatchException e) {
        System.out.println("Not a byte:"+scanner.next());
      }
    }
    scanner.close();
  }

  public static void stream() throws IOException {
    System.out.println("Reading with the FileInputStream Class:");
    FileInputStream d = new FileInputStream("target.txt");
    int b = -1;
    while((b = d.read()) != -1) {
      System.out.print((byte)b+" ");
    }
    d.close();
    System.out.println();
  }

  public static void main(String...args) throws IOException {
    scanner();
    stream();
  }
}

以下是 target.txt 的内容:

Next up is a byte:
6
Wasn't that fun?

这将产生以下输出:
Reading with the Scanner Class:
Not a byte:Next
Not a byte:up
Not a byte:is
Not a byte:a
Not a byte:byte:
A Byte:6
Not a byte:Wasn't
Not a byte:that
Not a byte:fun?
Reading with the FileInputStream Class:
78 101 120 116 32 117 112 32 105 115 32 97 32 98 121 116 101 58 10 54 10 87 97 115 110 39 116 32 116 104 97 116 32 102 117 110 63 

4
这些类实际上在做非常不同的事情。 FileInputStream 实际上是从输入文件中读取原始字节,而 Scanner 则将文件解析为以空格分隔的标记,并在你请求时尝试将每个标记转换为所需类型。
例如,如果你的输入文件长这样:
1

FileInputStream.read()将把1作为一个字节进行评估,并返回它的值:49Scanner.nextByte()将读取1并尝试将其评估为十进制整数正则表达式,然后给你:1

另一方面,如果您的输入文件包含

a

然后FileInputStream.read()会将a作为一个字节进行评估,并返回其值:97Scanner.nextByte()将读取a并尝试将其作为10进制的整数正则表达式进行评估,然后抛出java.util.InputMismatchException异常。


所以换句话说,Scanner.nextByte() 只读取文件中的整数对吗? - undefined

1
Scanner.nextByte()方法与FileInputStream.read()方法不同。 nextByte()方法将扫描输入的下一个标记作为字节。如果下一个标记无法转换为有效的字节值,则此方法将抛出InputMismatchException异常,如下所述。如果转换成功,则扫描器将超过匹配的输入。
如果下一个标记与上面定义的Integer正则表达式匹配,则该标记将被转换为字节值,就好像通过删除所有区域设置特定的前缀、组分隔符和区域设置特定的后缀,然后通过Character.digit将非ASCII数字映射到ASCII数字,如果存在区域设置特定的负前缀和后缀,则在前面添加负号(-),并将结果字符串传递给指定基数的Byte.parseByte
nextByte()方法尝试匹配一个数字的文本表示形式以将其存储为字节值。
另一方面,FileInputStream.read()将从输入流中读取一个字节数据。

参考:FileInputStream.read() Scanner.nextByte() Scanner.nextByte(int radix)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接