java scanner 写文件,使用java.util.Scanner逐字节读取文件

I'm trying to read a one line file character by character using java.util.Scanner. However I'm getting this exception":

Exception in thread "main" java.util.InputMismatchException: For input string: "contents of my file"

at java.util.Scanner.nextByte(Scanner.java:1861)

at java.util.Scanner.nextByte(Scanner.java:1814)

at p008.main(p008.java:18)

Here's my code:

public static void main(String[] args) throws FileNotFoundException {

File source = new File("file.txt");

Scanner scanner = new Scanner(source);

while(scanner.hasNext()) {

System.out.println((char)scanner.nextByte());

}

scanner.close()

}

Does anyone have any ideas as to what I might be doing wrong?

Edit: I realized I wrote hasNext() instead of hasNextByte(). However if I do that it doesn't print out anything.

解决方案

Why on earth would you want to use a scanner to read a file byte by byte? That's like using a wheelbarrow to transport your pocket change. (If you really need a wheelbarrow for your pocket change, let me know so I can become your friend).

But seriously: Class InputStream reads bytes from a file, simply and reliably, and does nothing else.

Class scanner was recently introduced into the Java API so textbook examples could pull data out of a file with less pain than is usually involved with using the cascade of new BufferedReader(new InputStream). Its specialty is inputting numbers and strings from free-form input files. The nextByte() method actually reads one or a few decimal digits from the input stream (if they're there) and converts the number thus scanned into a single byte value.

And if you're reading bytes, why do you want to output them as chars? Bytes are not chars, and brute-force interconverting will fail in some places. If you want to see the values of those bytes, print them out as they are and you'll see small integers between 0 and 255.

If you want to read chars from a file, FileReader is the class for you.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值