4
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.

Luca Geretti
  • 10,206
  • 7
  • 48
  • 58
ToBeGeek
  • 1,105
  • 4
  • 12
  • 20

6 Answers6

7

Try stripping any whitespace from the string:

        numberOfAttributes = Integer.parseInt(br.readLine().trim());
James Scholes
  • 7,686
  • 3
  • 19
  • 20
6

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.

Community
  • 1
  • 1
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
  • I had the exact same problem as OP but there weren't any solutions for it. I've been tearing my hair out because of this and realized that it's because of this exact problem you mentioned. Saved my stupid text file as ANSI encoding instead of UTF-8. Would like my 2 hours back. – Nopiforyou Apr 07 '14 at 16:49
1

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

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Read the return value in that documentation: "A String containing the contents of the line, **not including any line-termination characters**, or null if the end of the stream has been reached" – Silvio Mayolo Apr 21 '13 at 19:17
  • java.util.InputMismatchException, It gives me. – ToBeGeek Apr 21 '13 at 19:53
0

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.

Parth Soni
  • 11,158
  • 4
  • 32
  • 54
0

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?

user1883212
  • 7,539
  • 11
  • 46
  • 82
  • 1
    Nope. If you look carefully at the NumberFormatExceptions throw by each of your examples, you will find that they don't match the error given by the asker. – Luke Woodward Apr 21 '13 at 20:50
0

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

Avinav
  • 542
  • 5
  • 7