?
Solved

Read String and store into mutiple variable.

Posted on 2006-05-16
6
Medium Priority
?
267 Views
Last Modified: 2010-03-31
Hi, my .dat file looks something like this:

A|B|C|E|F#A1|B1|C1|E1|F1#A2|B2|C2|D2|E2|F2............................

I want to read this in a loop so that it has

var1=A
var2=B
var3=C
var4=D
var5=E

The character "#" would cause this to loop the read again.  Why would I do this you may ask? the reason is I want to create these variable so I can use them as my insert in the JDBC connection, such as insert into table A value (var1,var2,var3,var4,var5)....  This insert statment will get call as many time as there are number of "#" char in the file,
0
Comment
Question by:fylix0000
6 Comments
 
LVL 23

Expert Comment

by:brettmjohnson
ID: 16694637
You want to check out the Java StringTokenizer class:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html

Here is a tutorial:
http://www.devdaily.com/java/edu/pj/pj010006/pj010006.shtml

You will want to tokenize the string twice - once for #-delimited sections,
which you then parse based upon | delimiters.
0
 
LVL 14

Accepted Solution

by:
StillUnAware earned 1200 total points
ID: 16694709
This should do most of it:

FileInputStream fis = new FileInputStream(".dat");
byte c = 0;
int var = 0;
String[] vars = new String[5]; // this array is used instead of variables var1..var5, where var1 -> vars[0], ..., var5 -> vars[4]
while((c = fis.read()) != -1) {
    if((char)c == '#') {
        var = 0;
        //do the actions here, all variables (array 'vars') are filled with values
    } else if((char)c == '|') {
        var ++;
        vars[var] = "";
    } else {
        vars[var] += (char)c;
    }
}
fis.close();
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16696995
You can also use a do-while loop where the loop searches for the next '#' in the String using indexOf () and runs as long as the index is -1.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 13

Expert Comment

by:Webstorm
ID: 16698741
You can use StillUnAware's solution, if you add the following line :
    vars[0] = "";
just before the while loop. Otherwise you'll get a NullPointerException

0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 16701243
Well, you don't really need separate variable for each value, you simply can use array.

import java.util.regex.Pattern;
public class Split{
      public static void main(String[] args){
            String content = "A|B|C|E|F#A1|B1|C1|E1|F1#A2|B2|C2|D2|E2|F2";
            String[] blocks = content.split("#");
            for(int i=0; i<blocks.length; ++i){
                  String[] values = blocks[i].split("\\|");//It's a regular expression, so we need to escape special char
                  System.out.print("INSERT INTO table VALUES( ");
                  for(int j=0; j<values.length; ++j){
                        System.out.print(values[j]);
                        if(j<values.length-1){
                              System.out.print(",");
                        }
                  }
                  System.out.println(");");
            }

      }
}
0
 
LVL 3

Assisted Solution

by:Kanti
Kanti earned 800 total points
ID: 16701278
using Arrrays is better way of doing but as per your question this might help

   void FileToDB() {  

      DataInputStream dis = null;
      String FileRecord = null;
      int count = 0;
      String test = null;

      try {  

         File f = new File("c:\\YourFile.txt");
         FileInputStream fis = new FileInputStream(f);  
         BufferedInputStream bis = new BufferedInputStream(fis);  
         dis = new DataInputStream(bis);

         // read the file
         while ( (FileRecord = dis.readLine()) != null) {
               StringTokenizer st1 = new StringTokenizer(FileRecord, "#");
               while (st1.hasMoreTokens()){
              test = st1.nextToken();
            StringTokenizer st = new StringTokenizer(test, "|");
          {
            String var1 = st.nextToken();
            String var2 = st.nextToken();
            String var3  = st.nextToken();
            String var4 = st.nextToken();
            String var5 = st.nextToken();
            String var6 = st.nextToken();
           
//          you can insert your sql with var1 to var 6   values
          }
         }
        }

      } catch (IOException e) {  
         // catch io errors from FileInputStream or readLine()  
         System.out.println("Uh oh, got an IOException error: " + e.getMessage());  

      } finally {  
         // if the file opened okay, make sure we close it  
         if (dis != null) {
            try {
               dis.close();
            } catch (IOException ioe) {
               System.out.println("IOException error trying to close the file: " +
                                  ioe.getMessage());  
            }

         } // end if

      } // end finally

   } // end FileToDB
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month14 days, 22 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question