Reading long type from text file in Java

I am trying to read long types from a text file using a readLine()

class method BufferedReader

and then I parse the first token (long type number) with StringTokenizer

, but I am looking with an exception error which isjava.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 am reading from a text file and evaluating the long value for 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 is the error I am 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 grateful if you can help me and also thanks.

+3


source to share


3 answers


You probably have a tab character and not spaces to separate fields. Add a tab to your delimiter set ( " \t"

).



Also, always close your streams and readers in a finally block (only the outer part needs to be closed: closing the BufferedReader will close the InputStreamReader, which will close the FileInputStream).

+4


source


It is obvious that you are trying to analyze the non-numeric strings, the stack trace shows: 2481765933 Otna

. You have to 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 was much easier than using it StringTokenizer

. In fact, the usage is StringTokenizer

discouraged , almost obsolete - currently the preferred way of parsing a string - either use a method split()

for simple cases, or a class Scanner

for complex cases.

+4


source


You are using the wrong delimiter ( " "

) as your text file may contain more than one space character between tokens. StringTokenizer

is a deprecated class, don't use it unless you have a good reason. String.split () should suffice:

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

      

But I think Scanner is best 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 parse your example input correctly.

Here is the third fully working version of Java 6 .

+3


source







All Articles