Question

I have a csv file that contain one line;

'2013-05-25 23:59:59','-126125372','299134596','-1272989684','1826558680','-441013765','-441013765'

Every time the token encounter a space (e.g. "2013-05-25 23:59:59") it throws a error. Im using a StringTokenizer

Any idea how this happen?

Btw here's my code;

        Scanner x = new Scanner(new FileReader("c:\\test.csv"));
        StringTokenizer token = new StringTokenizer(x.next());           

        while (token.hasMoreElements())
        {
            System.out.println(token.nextElement()); 

        }
Was it helpful?

Solution

Assuming your CSV contains the line:

'2013-05-25 23:59:59','-126125372','299134596','-1272989684','1826558680','-441013765','-441013765'

The code you just posted

    Scanner x = new Scanner(new FileReader("c:\\test.csv"));
    StringTokenizer token = new StringTokenizer(x.next());           

will only capture '2013-05-25 as a String with x.next(), see the javadoc for Scanner#next(). From the javadoc,

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

So next() will return everything up to the next space as a String. Use nextLine() instead, to return the full line.

StringTokenizer token = new StringTokenizer(x.nextLine());  

OTHER TIPS

I assume x is an Iterator. whose next() method throws that exception. If you insist on using StringTokenizer legacy class, then check that there actually are more elements using x.hasNext() method.

use this

String str = "2013-05-25 23:59:59,'-126125372','299134596','-1272989684','1826558680','-441013765','-441013765'";
        StringTokenizer st = new StringTokenizer(str);

        System.out.println("---- Split by space ------");
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());
        }

you have invalid character(") 2013-05-25 23:59:59",' after 59.change it or skip it

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