扫描程序与FileInputStream

时间:2014-04-08 16:35:35

标签: java eclipse io

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

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

Scanner.nextByte()FileInputStream.read()之间的区别是什么?

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

为什么?

3 个答案:

答案 0 :(得分:4)

Scanner.nextByte()将读取下一个标记,如果它可以作为一个字节计算,则返回它,而FileInoutStream.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 

答案 1 :(得分:4)

这些课实际上做的事情非常不同。

FileInputStream实际上是从输入文件中读取原始字节,而Scanner正在将文件解析为以空格分隔的标记,并在您要求时将每个标记转换为请求的类型

例如,如果您的输入文件如下所示:

1

FileInputStream.read()会将1评估为一个字节,并返回其值:49Scanner.nextByte()会读取1并尝试将其评估为基数10的整数正则表达式,并为您提供:1

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

a

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

答案 2 :(得分:1)

Scanner.nextByte()FileInputStream.read().

不同

nextByte()方法将输入的下一个标记扫描为一个字节。如果下一个令牌无法转换为有效的字节值,则此方法将抛出 InputMismatchException ,如下所述。如果翻译成功,扫描仪将超过匹配的输入。

如果下一个标记与上面定义的Integer正则表达式匹配,则标记将转换为字节值,就像删除所有特定于区域设置的前缀,组分隔符和特定于区域设置的后缀一样,然后映射非ASCII数字通过Character.digit转换为ASCII数字,如果存在特定于区域设置的负前缀和后缀,则在前面添加一个负号( - ),并将结果字符串传递给具有指定基数的Byte.parseByte

即。 nextByte()方法尝试匹配数字的文本表示,以将其作为字节值存储。

另一方面,FileInputStream.read()将从输入流中读取一个字节的数据。

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