为什么我的BufferedReader读取的文本不会在给定文件中退出?

时间:2014-12-23 10:21:40

标签: java string byte bufferedreader

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

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

正在读取的文本文件中的行:

[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, 68, 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)

您可以看到异常,因为当bufferedReader从文件中读取时出现的字符被抛出(即使它们在文件中不存在)。如果有人能帮我弄清楚这些角色的来源以及它们出现的原因,那就太棒了!

3 个答案:

答案 0 :(得分:3)

您看到的是UTF-8 BOM

将输入文件转换为无BOM。

答案 1 :(得分:0)

Follow this code:

        String lineFromFile = bufferedReader.readLine();
        // strip out the `[` and `]`
        lineFromFile = lineFromFile.substring(1, lineFromFile.length()-1);
        StringBuilder sb = new StringBuilder();
        for(String s: lineFromFile.split(", "))
            sb.append((char) Integer.parseInt(s));
        String text = sb.toString();

答案 2 :(得分:0)

空格可能会导致此错误。在阅读行时尝试trim()输入行,

line = bufferedReader.readLine().trim();