本文介绍了扫描程序与FileInputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

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

Scanner.nextByte() FileInputStream.read()

我试图理解它,因为当我读取字节时(一个一个)来自一个简单文本的文件与 FileInputStream 它工作正常。但是当我使用扫描仪时, scanner.nextByte()不返回任何内容?

I am trying to understand it because when i read bytes (one by one) from a file with simple text with the FileInputStream it works fine. But when iam using Scanner the scanner.nextByte() doesn't return anything?

为什么?

推荐答案

Scanner.nextByte()将读取下一个标记,如果它可以作为一个字节进行计算,然后返回它,而FileInoutStream.read()将返回一个文件的每个字节。考虑这个例子:

The Scanner.nextByte() will read the next token and if it can be evaluated as a byte then return it while FileInoutStream.read() will return each byte of a file. Consider this example:

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

这篇关于扫描程序与FileInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 13:36