gpt4 book ai didi

java - 扫描仪与 FileInputStream

转载 作者:行者123 更新时间:2023-12-04 18:25:26 26 4
gpt4 key购买 nike

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

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

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

我试图理解它,因为当我使用 FileInputStream 从一个包含简单文本的文件中读取字节(一个一个地)时,它工作正常。但是当我使用 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

关于java - 扫描仪与 FileInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943067/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com