Search code examples
javaparseintnumberformatexception

How do you parse input from a text file in JAVA?


I tried to parse the String from my input.txt file, but I get the NumberFormatException thrown every time. I've added all the code that I have so far. I have tried .trim as well. I am very new to text files in Java; therefore, I have no idea what is wrong here. However, any bit of help would be appreciated.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Lab5_Exceptions_Redo extends Exception {

    public static void main(String[] args) throws FileNotFoundException {

        String file = "inputt.txt";
        String file1 = "outputt.txt";
        String file2 = "errorr.txt";

        PrintWriter errorr = new PrintWriter(file2);

        PrintWriter inputt = new PrintWriter(file);
        inputt.println(15951);
        // int whatever = Integer.parseInt(file);
        // System.out.print(whatever);
        inputt.close();
        Scanner scan = new Scanner(file);
        String number = scan.nextLine();
        int num = Integer.parseInt(number.trim());
        System.out.printf("%d", num);

        PrintWriter outputt = new PrintWriter(file1);
        outputt.println(num);
        outputt.close();
        // inputt.close();

        scan.close();
        // System.out.printf("%d", num);

        try {

        } catch (InputMismatchException e) {
            errorr.println("There was an input mismatch error.");
        } catch (NoSuchElementException e) {
            errorr.println("There is no such element.");
        } catch (UnsupportedOperationException e) {
            errorr.println("An unsupported operation occured.");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        errorr.close();

    }
}

Solution

  • You are doing a mistake. In Scanner constructor you should pass File object not String object. Since you are passing string "inputt.txt" its trying to parse this string and as a result you are getting NFE. Try this

    Scanner scan = new Scanner(new File(file));