java.lang.NumberFormatException: For input string: “22”

▼魔方 西西 提交于 2019-12-17 20:39:20

问题


public void loadFromFile(String filename) {
    File file = new File(filename);
    BufferedReader br;

    try {
        br = new BufferedReader(new FileReader(file));
        numberOfAttributes = Integer.parseInt(br.readLine());
    } 
    ...
}

Above is my program: I am trying to read from a txt file where the first line is the number 22 and nothing more. I don't know why the program gives me an exception.


回答1:


Try stripping any whitespace from the string:

        numberOfAttributes = Integer.parseInt(br.readLine().trim());



回答2:


I think you might have a UTF-8 BOM (byte-order mark) at the start of your file.

Here's a class that reproduces the error:

import java.io.*;

public class BomTest {
    public static void main(String[] args) throws Exception {
        File file = new File("example.txt");

        // Write out UTF-8 BOM, followed by the number 22 and a newline.
        byte[] bs = { (byte)0xef, (byte)0xbb, (byte)0xbf, (byte)'2', (byte)'2', 10 };
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(bs);
        fos.close();

        BufferedReader r = new BufferedReader(new FileReader(file));
        String s = r.readLine();
        System.out.println(Integer.parseInt(s));
    }
}

When I run this class, I get the following output:

luke@computer:~$ java BomTest 
Exception in thread "main" java.lang.NumberFormatException: For input string: "22"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:481)
        at java.lang.Integer.parseInt(Integer.java:514)
        at BomTest.main(BomTest.java:15)

There isn't really an easy way to deal with UTF-8 BOMs in Java; it's best not to generate them in the first place. See also this answer.




回答3:


br.readLine() reads the entire line including the new line special character.Apart, form the solution suggested by James, you can use Scanner#nextInt().




回答4:


try with numberOfAttributes = Integer.parseInt(br.readLine().trim());

public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.




回答5:


This happens because you have a space in the input line. Look at these:

int i1 = Integer.parseInt("22 ");
int i2 = Integer.parseInt("22a");
int i3 = Integer.parseInt("2 2");
int i4 = Integer.parseInt("22\n");

All of them generate exception. I suggest you to trim, tokenize or substitute. But in general, it doesn't sound to me a good solution to read a number from a file in that way. If you really need to store data, why don't you create an object ad hoc and serialize/deserialize it?




回答6:


You might have a null character in your string. Remove it using a regEx "\d+".

NumberFormatException is raised because the input string is not in expected number format. Generally, you can see 'the wrong string input' in the error message and can easily identify the bug. But in your case, the catch is that the error message does not display the string input completely (because it does not displays the null character).

Check the below output and the code.

public class TestParseInt{
    private static final Pattern pattern = Pattern.compile("\\d+");
    public static void main(String []args){
       String a = "22\0";
       try {
           System.out.println("Successfull parse a: " + Integer.parseInt(a));
       } catch(NumberFormatException e) {
           System.out.println("Error:" +e.getMessage());
       }
       try {
           Matcher matcher = pattern.matcher(a);
           if(matcher.find()) {
               System.out.println("Succesfull parse a: " + 
                Integer.parseInt(matcher.group(0)));
           }

       } catch(NumberFormatException e) {
           System.out.println("Error" + e.getMessage());
       }

    }
}

Output:

Error:For input string: "22"
Succesfull parse a: 22



来源:https://stackoverflow.com/questions/16135123/java-lang-numberformatexception-for-input-string-22

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!