Question

i'm trying to read long types from a text file with using readLine() method of BufferedReader class and then i parse the first token (which is long type number) with using StringTokenizer but i'm facing with an exception error which is java.lang.NumberFormatException

this is an example of my text file;

2764841629  Quaroten Ilen
1398844030  Orden Nenama
1185252727  Inja Nenaptin
2370429126  Quaren Inaja
1502141743  Otin Una
1993687334  Quarwennaja Nenoten
1015934104  Polen Meritna
2363674760  Otja Ie
1904629749  Neninin Ordja
3047965620  Algnaja Nenja

here is the code i read from a text file and assing the long value to my long variable

private void registerData() throws FileNotFoundException{
    try {

        String regPatName;
        String regPatSurname;
        long regPatID;


        FileInputStream fis = new FileInputStream("src\\assignment_3\\injuredPersonList.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(fis));

        String line;

        while( ( line = reader.readLine() ) != null) {

            StringTokenizer st = new StringTokenizer(line, " ");

            while(st.hasMoreTokens()){

                regPatID = Long.parseLong(st.nextToken());
                regPatName = st.nextToken();
                regPatSurname = st.nextToken();

                Patient regPatient = new Patient(regPatName, regPatSurname, regPatID);
                hashMethod(regPatient);
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(personTest.class.getName()).log(Level.SEVERE, null, ex);
    }


}

private void hashMethod(Patient regPatient){

    Long idPat = new Long(regPatient.getPatientID());
    int keyID;

    keyID = (int) Math.sqrt(Integer.parseInt(idPat.toString().substring(0, 5) + idPat.toString().substring(5, 10))) % (50000);

    System.out.println(keyID);

}

and finally this the error which i'm facing;

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "2481765933   Otna"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Long.parseLong(Long.java:419)
    at java.lang.Long.parseLong(Long.java:468)
    at assignment_3.personTest.registerData(personTest.java:58)
    at assignment_3.personTest.<init>(personTest.java:33)
    at assignment_3.personTest$1.run(personTest.java:161)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:641)
    at java.awt.EventQueue.access$000(EventQueue.java:84)
    at java.awt.EventQueue$1.run(EventQueue.java:602)
    at java.awt.EventQueue$1.run(EventQueue.java:600)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:611)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

i will be very appreciated if you can help me and also thanks anyway.

Was it helpful?

Solution

You probably have a tab character instead of spaces to separate your fields. Add the tab to your set of delimiters (" \t").

Also, always close your streams and readers in a finally block (only the outermost one must be closed: closing the BufferedReader will close the InputStreamReader, which will close the FileInputStream).

OTHER TIPS

Clearly you're trying to parse a non-numeric string, the stack trace shows it: 2481765933 Otna. You should split the input and parse the numeric part, something like this:

String[] data = line.split("\\s+");
regPatID = Long.parseLong(data[0]);
regPatName = data[1];
regPatSurname = data.length == 3 ? data[2] : "";

The above is much simpler than using StringTokenizer. In fact, the usage of StringTokenizer is discouraged, practically deprecated - nowadays, the preferred way to parse a string is either using the split() method for simple cases or the Scanner class for complex cases.

You are using the wrong delimiter (" ") since your text file may contain more than one space character between tokens. StringTokenizer is a legacy class, don't use it unless you have a good reason to. String.split() should suffice:

String[] result = line.split("\\s+");
regPatID = Long.parseLong(result[0]);
regPatName = result[1];
regPatSurname = result[2];

But I think that Scanner is the best fit for your problem:

// Java 7 try-with-resources synthax.
// If you are using Java <=6, declare a finally block after the catch 
// to close resources.
try (InputStream myFile = ClassLoader.getSystemResourceAsStream("MyTextFile.txt");
        Scanner sc = new Scanner(myFile)) {

    while (sc.hasNext()) {
        regPatID = sc.nextLong();
        regPatName = sc.next();
        regPatSurname = sc.next();

        System.out.printf("%d - %s %s\n", regPatID, regPatName, regPatSurname);
    }

} catch (Exception e) {
    // Do something about exceptions
}

Both versions correctly parses your example input.

Here is a third fully working Java 6 Version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top