How to retrieve IndividualStrings from a txt file using String Tokenizer.

hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
the data in my txt file looks like this way.
Data1;
abc; cder; efu; frg;
abc1; cder2; efu3; frg4;
Data2
sdfabc; sdfcder; hvhefu; fgfrg;
uhfhabc; gffjcder; yugefu; hhfufrg;
Data3
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
val1; val2; val3; val4; val5; val6;
i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
Regards,

Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
I would suggest something like this general framework:
//make a BufferedReader up here...
do
  String line = myBufferedReader.readLine();
  if (line!=null && line.trim().length()>0)
    line = line.trim();
    //do some processing on the line
while (line!=null);So what processing to do inside the if statement?
Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
strtok = new StringTokenizer(line, ";, ");
if (sectionNo==0)
  //read the tokens into the Labels1 collection
else if (sectionNo==1)
  //read the tokens into the Labels2 collection
else //sectionNo must be 2
  //create a new line in your table model and populate it with the token values...
}I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
Good luck.

Similar Messages

  • How to extract text from a PDF file using php?

    How to extract text from a PDF file using php?
    thanks
    fabio

    > Do you know of any other way this can be done?
    There are many ways. But this out of scope of this forum. You can try this forum: http://forum.planetpdf.com/

  • How to extract data from a .txt file & send it to a serial port automatically

    Hi all
    I'm a final yr B.Tech student. I am new to the entire LABVIEW thing. But i hear its really good. My dept. in collge has purchased labview & i'm tryng to use it
    As i'm new to labview , i need help plz
    " I want to open a .txt file (in my PC) & transmit all the contents of the file via serial (COM) port to an 89%! microcontroller. Also i want to read the feedback messages from the microcontroller thru the serial port & save it to the same file in the PC.All this must be done automatically. ie, no manual intervention after execution starts"
    Kindly help me as i'm stuck here & unable to proceed further with my project

    here is my 20min try without debugging (needs a rs232 and loopback connector )
    use the probe and highlight the dataflow to see how it works.
    as always:  there are many ways to solve your problem
    Greetings from Germany
    Henrik
    LV since v3.1
    “ground” is a convenient fantasy
    '˙˙˙˙uıɐƃɐ lɐıp puɐ °06 ǝuoɥd ɹnoʎ uɹnʇ ǝsɐǝld 'ʎɹɐuıƃɐɯı sı pǝlɐıp ǝʌɐɥ noʎ ɹǝqɯnu ǝɥʇ'
    Attachments:
    read write file to RS232.vi ‏69 KB

  • How to read data from a .txt file?

    currently i'm under study on java
    while need to extract data from a hyperterminal or .txt file
    could any one help me in this problem.?
    as in txt or .ht got their own overhead .( or what u call it. tt identify the file type)
    so how to open it and read data one ah?
    thanks all.

    Here's a code snippet 4 u
    String sInput = null;
    FileInputStream sStream = new FileInputStream("yourTxtFile");
    BufferedReader fileIn = new BufferedReader(new InputStreamReader(sStream));
    while((sInput = fileIn.readLine()) != null){
    System.out.println(sInput);
    hope this help
    *-)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to retrieve data from an Excel file which is located on server

    hi everybody,
                    I am using SAP NWDS 2004s .     
                I have done an application on how to export the table data into an Excel .
    Now i want to get the data from an Excel file which is located in server and display that data which is in excel in a View for example a Sample view in Webdynpro  .
    In Sample view i took a uielement textview to display the data ....   
    can any one help how to procced further
    Thanks in advance
    Madhavi

    Options to read Excel data to WebDynpro context
    Reading Excel Sheet from Java without using any Framework
    Reading Multiple Sheets of Excel Sheet from Java
    Few Threads
    How to Display the content of Excel file into Webdynpro Table
    Is it possible to upload data from excel file(.xls)
    Re: How to export the data as integer into excel sheet?
    regards
       Vinod

  • How to read data from a .txt file in real time

    Hi
    I am running a fortran code which takes around 1 week to run and output data are continuously saved in .txt files. I want to display these data and plot it against time in labview.
    Lets say I have a array of real numbers starting from 1.0 , and every 2-3 sec another number is added (output of code). So I dont want end-of-file-reached error in my program and also want program to wait until next data is updated in .txt file.
    I tried to make a simple read_txt_file.vi, but I am getting problems in terms of continous reading. Help !! Help !!
    Pl see the attached vi.
    Thanx
    PKJ
    Attachments:
    FileReader.vi ‏43 KB
    labview.txt ‏18 KB

    Hi PKJ,
          I modified your VI and it seems to do what you asked, that is, display the data from a file as the data is being added.
    Hope it helps!
    Message Edited by Dynamik on 11-08-2005 04:32 PM
    Message Edited by Dynamik on 11-08-2005 04:34 PM
    When they give imbeciles handicap-parking, I won't have so far to walk!
    Attachments:
    FileReader.vi ‏52 KB

  • Photoshop album starter edition 3.2  how to retrieve photos from obsolete locked file?

    photoshop album starter edition 3.2   how to retri
    eve photos from obsolete locked file?

    Try in that product's forum
    http://forums.adobe.com/community/ps_album_starter

  • How can i delete a UserName  from a text file using Strings or io.

    hi i m trainee
    i have been assigned to make java program which deletes a UserName and
    his Passwor from a Text File
    i m unable to do it using the code below
    plz help
    do reply
      import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java .applet.*;
    import java.io.*;
    class Del extends JFrame  implements ActionListener
         String s2;
         JTextField CWDMUserDText = new JTextField();
         JButton CWDMSecDelButton = new JButton("DELETE");
         JLabel CWDMUserLabel = new JLabel("USER NAME");
         JPasswordField CWDMPassDText = new JPasswordField();
         JLabel CWDMPassLabel = new JLabel("PASSWORD");
         //String user,pass;
         /* CONSTRUCTOR*/
              Del()
                   Container contentPane=getContentPane();
                   contentPane.setLayout(null);
                  setLocation(400,200);
                   contentPane.add(CWDMUserDText);
                   contentPane.add(CWDMSecDelButton);
                   contentPane.add(CWDMUserLabel);
                   contentPane.add(CWDMPassDText);
                   contentPane.add(CWDMPassLabel);
                  CWDMUserLabel.setBounds(20,70,100,25);
                  CWDMPassLabel.setBounds(20,100,100,25);
                   CWDMUserDText.setBounds(150,70,100,25);
                   CWDMPassDText.setBounds(150,100,100,25);
                   CWDMSecDelButton.setBounds(80,135,100,25);
                   CWDMUserDText.addActionListener(this);
                   CWDMPassDText.addActionListener(this);
                   CWDMSecDelButton.addActionListener(this);
                   contentPane.setBackground(Color.CYAN);
                   setVisible(true);
                   setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent ae)
                  if(ae.getSource()==CWDMSecDelButton)
         //             user = CWDMUserDText.getText();
         //          pass = CWDMPassDText.getText();
         //          showarr();
                   s2 = CWDMUserDText.getText();
                   CWDMUserDText.setText("");
                   CWDMPassDText.setText("");
                   DelUser(s2);
              public static void main(String args[])
                   Del myframe1= new Del();
                   myframe1.setSize(300,200);
                   myframe1.setVisible(true);
              public void DelUser(String s)
                   //int a;
                   try
                        FileReader fr = new FileReader("file.txt");
                        BufferedReader br = new BufferedReader(fr);
                       String s1;
                       int a;
                       int len = s.length();
                       System.out.println(len);
                       //s2 = CWDMUserDText.getText();
                        while ((s1=br.readLine()) !=null)
                             if((a=s1.indexOf(s))>0 && (a=s1.indexOf(s))!=0)
                                  System.out.println(a);
                        fr.close();
                   catch(FileNotFoundException e)
                        System.out.println("exception occured");
                   catch(IOException e)
                        System.out.println("io");
         }

    Some tips:
    1) If you are adding or deleting stuff from a text file you need to write a new, modified file and then, optionally, do something like:
    rename the old file to whatever.bak or the like.
    rename the new file to the old.
    2) Don't depend on System.out so much on a GUI application. For example if you get an exception use javax.swing.JOptionPane to display an alert (and show the message from the exception). You can write the stack trace to System.out if you want.
    3) Don't muck about with calculating bounds for screen objects, let a layout manager sort it out. I like BoxLayoutManager for most things like this.
    4) For bonus points do your IO in a separate Thread. Generally you don't want anything happening in an actionPerformed method which significantly delays it's return. The method should launch a new Thread to do the job, and disable the button until the Thread finishes.

  • How to read data from the excel file using java code.

    Hi to all,
    I am using below code to getting the data from the excel file but I can't get the corresponding data from the specific file. can anyone give me the correct code to do that... I will waiting for your usefull reply......
    advance thanks....
    import java.io.*;
    import java.sql.*;
        public class sample{
                 public static void main(String[] args){
                      Connection connection = null;
                          try{
                               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                               Connection con = DriverManager.getConnection( "jdbc:odbc:Mydsn","","" );
                               Statement st = con.createStatement();
                               ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );
                               System.out.println("sample:"+rs);
                                  ResultSetMetaData rsmd = rs.getMetaData();
                                  System.out.println("samplersd:"+rsmd);
                               int numberOfColumns = rsmd.getColumnCount();
                                  System.out.println("numberOfColumns:"+numberOfColumns);
                                   while (rs.next()) {
                                            System.out.println("sample1:"+rs);
                                            for (int i = 1; i <= numberOfColumns; i++) {
                                                 if (i > 1) System.out.print(", ");
                                                 String columnValue = rs.getString(i);
                                                 System.out.print(columnValue);
                                            System.out.println("");
                                       st.close();
                                       con.close();
                                      } catch(Exception ex) {
                                           System.err.print("Exception: ");
                                           System.err.println(ex.getMessage());
                        }

    1: What is the name of the excel sheet?
    2: What is printed in this program? null ? anything?
    error?Excel file name is "sample.xls" I set excel file connectivity in my JDBC driver(DSN). Here in my program I am not giving that excel file name. I am giving only that excel sheet name. that is followed
    ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );The output of this program is given bellow.
    sample:sun.jdbc.odbc.JdbcOdbcResultSet@1b67f74
    samplersd:sun.jdbc.odbc.JdbcOdbcResultSetMetaData@530daa
    numberOfColumns:2

  • How to load variables from a .txt file

    Hi.
    I usually make a flash aplication in colaboration with a php
    programmer. But i want to test my swfs without having to wait for
    him. So i want to do that through a text file. I know that flash
    can load variables from text files. The problem is i don't know how
    to format the text file ( example.txt).
    Thank you

    Here's a couple of ideas.
    First you probably want to change what you have...and put
    your 'if (pVar==1' etc inside a separate function and call it from
    the onLoad handler after you have assigned the value to pVar...
    because the onLoad will run at some unknown point in time after
    loading has finished (actually in the test environment this might
    work... but that wouldn't be the same as what happens in a
    production setting).
    To create test files for loadvars... simply create a new as2
    file and put this code on the first frame and test movie:

  • How to retrieve resources from a jar file ?

    Hello,
    Currently, I have application classes in a jar file, and all other resources (pictures, properties, and so forth..) in my windows folder. I do not have any problem for using them such way. For example to set an icon to a JFrame I have coded :
    f.setIconImage("mypicture.jpg");To make installation easier, I'd like to put my picture into the jar file with the classes. Is it possible ? if so, how should I modify my code to make things work ? Should I specify a special path ?
    Thanks for all
    Gege

    Thanks a lot, I'm going to try both ways.What both ways? Both replies are about the same thing -- using the classpath to find resources.
    The question now is what about if there is the same file
    name in the jar file and also in the directory ? Is
    there a search hierarchy ?It will find the first one it encounters in the classpath. You shouldn't have 2 resources with the same name in the classpath -- that's just like having two classes with the same package and class name.

  • How to retrieve data from a REF CURSOR using OCI 8.0?

    I found an example in Oracle docs (shown below) that discusses how to bind a REF CURSOR for later data retrieval, but it does not explain actually how to do the later data retrieval.
    I hope someone can explain it to me. Thanks
    The OCI provides the ability to bind and define PL/SQL REF CURSORs and nested tables. An application can use a statement handle to bind and define these types of variables. As an example, consider this PL/SQL block:
    static const text plsql_block = (text )
    "begin \
    OPEN :cursor1 FOR SELECT empno, ename, job, mgr, sal, deptno \
    FROM emp_rc WHERE job=:job ORDER BY empno; \
    OPEN :cursor2 FOR SELECT * FROM dept_rc ORDER BY deptno; \
    end;";
    An application would allocate a statement handle for binding, by calling OCIHandleAlloc(), and then bind the :cursor1 placeholder to the statement handle, as in the following code, where :cursor1 is bound to stm2p. Note that the handle allocation code is not included here.
    err = OCIStmtPrepare (stm1p, errhp, (text *) nst_tab, strlen(nst_tab),
    OCI_NTV_SYNTAX, OCI_DEFAULT);
    err = OCIBindByName (stm1p, (OCIBind **) bndp, errhp,
    (text *)":cursor1", (sb4)strlen((char *)":cursor1"),
    (dvoid *)&stm2p, (sb4) 0, SQLT_RSET, (dvoid *)0,
    (ub2 *)0, (ub2 *)0, (ub4)0, (ub4 *)0, (ub4)OCI_DEFAULT);
    In this code, stm1p is the statement handle for the PL/SQL block, while stm2p is the statement handle which is bound as a REF CURSOR for later data retrieval. A value of SQLT_RSET is passed for the dty parameter.

    ( sorry, i forgot the Link where i get this html fiLes, so i just copy-paste here )
    ( maybe it can heLp you a bit. -- it's heLp me, for sure )
    And the following is thanks to Brett Rosen :
    I noticed that you didn't have an OCI entry
    on http://osi.oracle.com/~tkyte/ResultSets/index.html .
    Here is OCI code to do this (Oracle 81) if you want to include it on
    that page.
    Some error checking and cleanup has been removed, but the below should
    work. (once dbname has been replaced appropriately)
    Brett
    int main(int argc, char* argv[])
    OCIError* pOciError;
    char* pConnectChar = "dbname";
    char* pUsernameChar = "scott";
    char* pPasswordChar = "tiger";
    int answer;
    OCIStmt* pOciStatement;
    char* sqlCharArray = "BEGIN :success := sp_ListEmp; END;";
    int id;
    char ename[40];
    OCIEnv* g_pOciEnvironment = NULL;
    OCIServer* g_pOciServer = NULL;
    OCISession* g_pOciSession = NULL;
    OCISvcCtx* g_pOciServiceContext = NULL;
    sb2* pIndicator=0;
    sb2* pIndicator2=0;
    sb2* pIndicator3=0;
    OCIDefine* pOciDefine;
    OCIDefine* pOciDefine2;
    OCIBind* pBind;
    OCIStmt* cursor;
    answer = OCIInitialize(OCI_THREADED, NULL, NULL, NULL, NULL);
    answer = OCIEnvInit(&g_pOciEnvironment, OCI_DEFAULT, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciSession, OCI_HTYPE_SESSION, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServer, OCI_HTYPE_SERVER, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL);
    answer = OCIServerAttach(g_pOciServer, pOciError, (unsigned char *)pConnectChar, strlen(pConnectChar),
    OCI_DEFAULT);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pUsernameChar, strlen(pUsernameChar),
    OCI_ATTR_USERNAME, pOciError);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pPasswordChar, strlen(pPasswordChar),
    OCI_ATTR_PASSWORD, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciServer, 0, OCI_ATTR_SERVER, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciSession, 0, OCI_ATTR_SESSION, pOciError);
    answer = OCISessionBegin(g_pOciServiceContext, pOciError, g_pOciSession, OCI_CRED_RDBMS, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&pOciStatement), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray, strlen(sqlCharArray),
    OCI_NTV_SYNTAX, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&cursor), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIBindByPos(pOciStatement,&pBind, pOciError, 1, &cursor, 0,SQLT_RSET,
    pIndicator2, 0,NULL, 0,0,OCI_DEFAULT);
    answer = OCIStmtExecute(g_pOciServiceContext, pOciStatement, pOciError, 1, 0, NULL, NULL,
    OCI_COMMIT_ON_SUCCESS);
    answer = OCIDefineByPos(cursor,&pOciDefine, pOciError,2,&id,sizeof(int),
    SQLT_INT,pIndicator, 0, 0,OCI_DEFAULT);
    answer = OCIDefineByPos(cursor,&pOciDefine2, pOciError,1,ename,40,
    SQLT_STR,pIndicator3, 0, 0,OCI_DEFAULT);
    if (answer == 0)
    while ((answer = OCIStmtFetch(cursor,pOciError, 1,OCI_FETCH_NEXT,OCI_DEFAULT)) == 0)
    printf("fetched id %d and name %s\n",id,ename);
    answer = OCIHandleFree(pOciError, OCI_HTYPE_ERROR);
    return 0;
    }

  • How do I upload/download a txt file using struts

    what do I need on my JSP page and how do I implement this functionality in an action?

    both work differently
    upload: <html:file tag (i thin) with a FormFile property in your ActionForm
    download use a servlet that uses the outputstream from hte response to send the file

  • CS3: How to generate PDF from multiple HTML files using CSS?

    I have a set of static HTML files. They are nicely formatted using a single style sheet. They interlink. I would like a way to generate a single PDF file from that set of HTML files that preserves the links (of course, they would all link within the single generated PDF because they would not longer be separate files as a PDF). I would also like to preserve the formatting from the CSS so it doesn't look generic. I own CS3 but don't know which tool to use for this, if any. Which tool would I use for this?

    Acrobat Pro

  • How to insert text from saved text file using line number to indesign document to specific cursor point?

    i'm using indesign for make books. always i need insert quotes from some holy books. so i need to insert text using verse number

    i'm not asking about
    b
    u
    l
    l
    e
    t and
    n
    u
    m
    b
    e
    r
    i
    n
    g
    sorry for my bad english
    my target is simply insert pre typed sorted texts using the verse number. for example. i have Holy Quran full text . it have about 6000 verse. suppose i need chapter 3, verse 5 in to my paragraph. manually i goto that text file and copy the text paste it here. but i need it automatically using page number/ verse number/ unique id. script / addins .
    approximately like "data merge " in design.

Maybe you are looking for

  • How do i change the path of data ajax false from returning to homepage, when using a PHP mail form in jquery mobile?

    I have a put a php mail form in the quote page of my mobile site. However when i send the form it returns to the route page rather than the quote page, i have used the data ajax false action as i dont want to send via ajax. i have left the thanks pag

  • How do i transfer songs from my ipod classic to another ipod classic?

    How do I transfer music form one Ipod classic to another?

  • Problema con photoshop cc

    Buenas tardes, Mi problema es el siguiente: Cuando intento abrir una imágen cualquiera (jpg,png), no abre nada, es decir, sigo viendo la pantalla gris como si no hubiera hecho nada. Tengo windows 8 64 bits, por lo que instalé la versión para 64bits,

  • Planning table ( REM)

    Hi Experts,              When we opening planning table (mf50) with material selection ,then complete capacity data  section is not appearing& in header view of capacity requirement planning (change capacity display isin grey color). we have already

  • Today's Forum Bug - Image Gone Missing

    I'd like to think the forum is a repository where answers to one person's questions can end up helping others in the future. But that kind of goes to hell in a hurry if the forum loses supporting image information... Exhibit A:   A forum thread with