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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sorry, yours wasn't there when I was typing mine :)
never mind ;-)
ASKER
how do I read line by line ?
As explained in the link which CEHJ posted.
ASKER
sorry ... how do I use StringTokenizer ? may i have an example ?
StringTokenizer st = new StringTokenizer(line, " ,");
while(st.hasMoreTokens()) {
String token = st.nextToken();
}
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();
}
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] ) ;
String[] array = line.split ( " " ) ;
int i = Integer.parseInt ( array[0] ) ;
:-)