The Artima Developer Community
Sponsored Link

Java Answers Forum
Using String Tokenizer

1 reply on 1 page. Most recent reply: Jan 8, 2003 8:20 PM by Ugo Posada

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
neo

Posts: 1
Nickname: neo1
Registered: Dec, 2002

Using String Tokenizer Posted: Dec 27, 2002 3:44 PM
Reply to this message Reply
Advertisement
Hello all,
the following code reads from a file and outputs it into another file. I want to using String Tokenizer to output a certain line in the following format.The input file is a .csv file (comma separated)
eg: if a line in the input file is:
344, sadf, 45, fdklj
321, dsff, 49, lkjah
then i want the output to be:
321
dsff
49
fdlkj
if the first column is 321, else the message should be item not found.
The code i have written is as follows:
import java.io.*;

class FileReadTest {

//--------------------------------------------------< main >--------//

public static void main (String[] args) {
FileReadTest t = new FileReadTest();
t.readMyFile();
}


//--------------------------------------------< readMyFile >--------//

void readMyFile() {

String record = null;
int recCount = 0;

try {

FileReader fr = new FileReader("D://bcd.csv");
BufferedReader br = new BufferedReader(fr);

record = new String();

while ((record = br.readLine()) != null) {
recCount++;
System.out.println(recCount + ": " + record);
}


} catch (IOException e) {
// catch possible io errors from readLine()
System.out.println("Eeks, got an IOException error!");
e.printStackTrace();
}

please help me include the string tokenizer.


Ugo Posada

Posts: 37
Nickname: binaryx
Registered: Dec, 2002

Re: Using String Tokenizer Posted: Jan 8, 2003 8:20 PM
Reply to this message Reply
This is what I extracted from the j2se API javadoc

StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         println(st.nextToken());
     }


The only thing you need to do is passing each line to the tokenizer telling the correct delimiter, for instance:

StringTokenizer st = new StringTokenizer("234;789;joe;rachel", ";"); 
 
while (st.hasMoreTokens()) {
         println(st.nextToken());
     }


Then you use what is inside the while loop to do whatever you want to do with each item, for instance, the console output for the last case would be:

234
789
joe
rachel

Regards

Ugo Posada Zabala
Universidad de los Andes
Bogot? - Colombia

Flat View: This topic has 1 reply on 1 page
Topic: Splitting a String to a specific length Previous Topic   Next Topic Topic: com package for Java required

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use