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




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


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

我试图理解它,因为当我从带有FileInputStream的简单文本文件中读取字节(一个接一个)时,它工作正常。但是当iam使用Scanner时,scanner.nextByte()不返回任何内容吗?

这是为什么?

最佳答案

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

07-27 19:19