0

I have a text file that contains one number, and I'm loading it using this method:

BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("res/sheet.cfg"));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append('\n');
            line = br.readLine();
        }
        textureSize = Integer.valueOf(sb.toString());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This line:

textureSize = Integer.valueOf(sb.toString());

Throws this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "16"

I understand what the issue is, but how do I fix it? Do I need to create a temporary string to remove the quotations and then get the value of that string and pass it into textureSize?

2 Answers 2

5

This is the problem

sb.append('\n');

dont do it. Integer.valueOf accepts only digits in the input string, new line is not allowed

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Works perfectly! So Java automatically adds quotations to new lines?
5

Integer.valueOf does not allow trailing or leading whitespace characters. Trimming the string before parsing should fix the problem:

textureSize = Integer.valueOf(sb.toString().trim());

Better yet, remove code that adds newline in the first place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.