本文介绍了为什么我的BufferedReader读取未在给定文件中退出的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 BufferedReader 从文件中读取存储为字节的详细信息,然后转换 bytes 转换为文本并将其拆分为数组。但是我的程序从从文件读取的文本中返回了 NumberFormatException 。在下面,我提供了代码,错误消息,从文件中读取的行以及用于显示 BufferedReader 从文件中读取的内容的打印语句。

I am using a BufferedReader to read details from a file which are stored as bytes, I am then converting the bytes into text and splitting it into an array. However my program is returning a NumberFormatException from the text read from the file. Below I have provided my code, the error message, the line read from the file and the print statement used to show what the BufferedReader has read from the file.

FileReader fileReader = new FileReader("VirtualATM.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
System.out.println(line);
String line = line.substring(1, line.length()-1);   //Convert bytes read back to String
StringBuilder sb = new StringBuilder();
for(String s: line.split(", ")) //Split every byte on ,
sb.append((char) Integer.parseInt(s));  //Convert byte to char
String text = sb.toString();    //Convert StringBuilder to String
String [] cardNum = text.split("\\s+"); //Split line read from file on every blank space into an array

文本文件中的行被读取:

Line in the text file that is being read:

[78,97,109,101,32,116,101,115,116,32,99,97,114 ,100、78、111、32、54、55、56、56、55、53、55、49、57、32、67、117、114、114、101、110、116、32、66、97、108 ,97、110、99、101、32、51、55、48、32、111、118、101、114、100、114、97、102、116、32、102、97、108、115、101、32 ,111、118、101、114、68、114、97、102、116、76、105、109、105、116、32、48、32、112、105、110、32、50、53、50、53 ]

打印语句中的行- System.out.println(line)

[[78,97,109,101,32,116,101,115,116,32,99,97,114 ,100,78,111,32,
54,55,56,56,55,53,55,49,57,32,67,117,114,114,101,110,116,32,6
6,97,108,97,110,99,101,32,51,55,48,32,111,118,101,114,100,114,
97,102,116, 32、102、97、108、115、101、32、111、118、101、114、6 8,114,97,1
02,116,76,105,109,105,116,32,48,32,112,105,110,32,50,53,50,53]

抛出异常:

Exception in thread "main" java.lang.NumberFormatException: For input string: "»¿[78"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)

可以看到由于在缓冲区reader从文件读取(即使文件中不存在)时出现的字符?»而引发了该错误。如果有人可以帮助我弄清楚这些字符来自何处以及为什么出现,那就太好了!

The exception, as you can see is thrown because of the characters  which are appearing when the bufferedReader reads from a file (even though they don't exist in the file). If anyone could help me figure out where these characters are coming from and why they are appearing, that would be great!

推荐答案

您会看到

将输入文件转换为不含BOM。

Convert your input file to be without BOM.

这篇关于为什么我的BufferedReader读取未在给定文件中退出的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:39