Link to home
Start Free TrialLog in
Avatar of meow00
meow00

asked on

read data from files ...

Hello experts,

   How do I read from a text file such as:

myData.txt
--------------------
0, Data, hello, world, 3
1, Data1, meow, woof
-----------------------

  if the input is numeric value -> do A
  if the input is String -> do B

  many thanks.
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, yours wasn't there when I was typing mine :)
never mind ;-)
Avatar of meow00
meow00

ASKER

how do I read line by line ?
As explained in the link which CEHJ posted.
Avatar of meow00

ASKER

sorry ... how do I use StringTokenizer ? may i have an example ?
StringTokenizer st = new StringTokenizer(line, " ,");
while(st.hasMoreTokens()) {
    String token = st.nextToken();
}
You can avoid all those conversion/tokenizing problems by using a Scanner:

      Scanner in = null;
      try {
            in = new Scanner(new FileInputStream("data.txt"));
            in.useDelimiter("[\\s,]");
            while (in.hasNext()) {
                  if (in.hasNextInt()) {
                        doNumber(in.nextInt());
                  }
                  else if(in.hasNext()) {
                        doText(in.next());
                  }
            }
      }
      finally {
            in.close();
      }
Or just use split ():

String[] array = line.split ( " " ) ;
int i = Integer.parseInt ( array[0] ) ;
:-)