Read String and store into mutiple variable.

Posted on 2006-05-16
Last Modified: 2010-03-31
Hi, my .dat file looks something like this:


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


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,
Question by:fylix0000
    LVL 23

    Expert Comment

    You want to check out the Java StringTokenizer class:

    Here is a tutorial:

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

    Accepted Solution

    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 = != -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;
    LVL 30

    Expert Comment

    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.
    LVL 13

    Expert Comment

    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

    LVL 7

    Expert Comment

    by:Igor Bazarny
    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){

    LVL 3

    Assisted Solution

    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 {
                } catch (IOException ioe) {
                   System.out.println("IOException error trying to close the file: " +

             } // end if

          } // end finally

       } // end FileToDB

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    Suggested Solutions

    An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
    Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
    This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

    733 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

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now