Reading a text file with different delimiters using Scanner

Hello,
I'm trying to read text from a file using ", " as a delimiter between Strings using a Scanner. I tried reading one line and then using the split() method in the string class, split each string by it's delimiter. I tried using an ArrayList to store each split token and the compiler is giving me some sort of syntax error when I'm pretty sure its right. If help can be given, it would be greatly appreciated. Thank you
Here's my code
Scanner input = new Scanner(backupFile);
input.useDelimiter("[, ]");
while (input.hasNext()) {
ArrayList<String> list = new ArrayList<String>();
String s = input.nextLine();
String delims = "[, ]";
list.add(s.split(delims));
for(int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
list.clear();
}

s.split(delims) will return an array of strings, not a string. So you need to declare list as an array list of such arrays:ArrayList<String[]> list = new ArrayList<String[]>();(It's a good idea to copy and post compiler messages here, so no-one has to guess. Likewise indicate which line of your code they are referring to.)
[Edit]If it only the contents of the array you wish to put in the array, then you can just say List list = Arrays.asList(s.split(delims));

Similar Messages

  • Reading fixed length file with different record types

    Hi,
    I need to read a fixed-length file with different record types, but the record identifier is in 31st position and not in 1st position.
    But if I give 31 as position in File adpater wizard, BPEL takes whole 1-31 as identifier.
    How we need to read such files.
    Thanks
    Ravdeep

    hi ,
    u cannot use the default wzard for this
    use some thing like this nxsd:lookAhead="30" nxsd:lookFor="S"have a look at the below link it has some examples
    http://download.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/nfb.htm

  • SSIS project - read multiple flat files with different formats

    hi all,
    i need to import multiple flat files with different formats into different tables of the sql server database and not able to figure out the best way out in ssis to do so...
    please advise the possible methods in ssis to do so and if possible the process which can be dynamic as file names or columns might change in future.

    Hi AK1987,
    To import flat files with dynamic columns, we can use Script Task inside a Foreach Loop Container to parse the first row of the flat file to get the columns names and save them into a .NET variable, then, we can create “Create Table” script based on this
    variable, and then store the script into a SSIS package variable. After that, we create a staging table based on the package variable, load the flat file data to the staging table. Eventually, we load data from the staging table to the destination table. For
    the detail steps, please walk through the following blog:
    http://www.citagus.com/citagus/blog/importing-from-flat-file-with-dynamic-columns/ 
    Regards,
    Mike Yin
    TechNet Community Support

  • Reading a text file with GUI_UPLOAD

    Hello,
      I'm trying to read a text file into an internal table of text lines using GUI_UPLOAD. The problem is that I can only read a maximum of 255 characters from each line. So for example, if the first line in the text file contains 260 characters, I lose the last 5 characters of that line.
      Any ideas on how to read the ENTIRE contents of a text file into an internal table of text lines? I'd really appreciate any help!
    CALL METHOD cl_gui_frontend_services=>gui_upload
      EXPORTING
        filename                = 'c:\example.txt'
      FILETYPE                = 'ASC'
      HAS_FIELD_SEPARATOR     = SPACE
      HEADER_LENGTH           = 0
      DAT_MODE                = SPACE
      CODEPAGE                = SPACE
      IGNORE_CERR             = ABAP_TRUE
      REPLACEMENT             = '#'
      READ_BY_LINE            = 'X'
    IMPORTING
      FILELENGTH              =
      HEADER                  =
      CHANGING
        data_tab                = int_textline
      EXCEPTIONS
        file_open_error         = 1
        file_read_error         = 2
        no_batch                = 3
        gui_refuse_filetransfer = 4
        invalid_type            = 5
        no_authority            = 6
        unknown_error           = 7
        bad_data_format         = 8
        header_not_allowed      = 9
        separator_not_allowed   = 10
        header_too_long         = 11
        unknown_dp_error        = 12
        access_denied           = 13
        dp_out_of_memory        = 14
        disk_full               = 15
        dp_timeout              = 16
        not_supported_by_gui    = 17
        error_no_gui            = 18
        OTHERS                  = 19.
    IF sy-subrc <> 0.
    error handling
    ENDIF.
    thanks,
    Ahmad

    Hi Ahmad,
    The function module can take more that 255 characters. Just follow the declaration Raja suggested. It is working for me.
    DATA: BEGIN OF it_datatab OCCURS 0,
      row(500) TYPE c,
    END OF it_datatab.
    CALL FUNCTION 'GUI_UPLOAD'
      EXPORTING
        filename        = 'c:\test.txt'
        filetype        = 'ASC'
      TABLES
        data_tab        = it_datatab
      EXCEPTIONS
        file_open_error = 1
        OTHERS          = 2.
    Thanks
    Vinod

  • Read two lvm files with different length

    I'm trying to read to same graph two different measurements with same starting point, starting point is OK.
    But when the shorter file is coming to the end the VI stops with following message:
    "Possible reason(s):
    LabVIEW:  End of file encountered.
    =========================
    NI-488:  Invalid argument or arguments to function call."
    How can I come over this and get both measurements into same graph in their full length with same starting point?
    PS I have attached the VI file, a short and a long measurement file. Changed the file extension from LVM to TXT
    Attachments:
    Read_duo.vi ‏128 KB
    SE1100_ny_1.txt ‏249 KB
    SE1100_ref_1.txt ‏468 KB

    Hi,
    Apprently your LabVIEW is set with the option "enable automatic error handling", you can change this in tools >> options block diagram untick the option.
    Doing this will only get ride of the dialog when the error occurs but not get read of the error.
    So you are reading your files chunk by chunk in your while loop, so at some point you will get to the end of your files, when you do the VI you are using return an error 4 "end of file reached", from here you have different possibilities, if you want to be able to read files that have different length, here is a quick way to ignore the "end of file" error on both files independantly.
    Hope this helps
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"

  • Read from spreadsheet file with multiple delimiters

    Is there a way to specify multiple delimitors in the read from spreadsheet file vi? I have a file that i need to read in that contains both space and comma delimitors and would like to read that data into an array using both delimitors (or not and). Below is the data I'm trying to read.
    ;attenuator data table
    att00:   db       000h,015h,017h,035h,03Ch,03Eh,03Eh,05Ch,05Eh,05Eh
    att10:   db       07Ch,07Eh,07Fh,09Dh,09Fh,09Fh,0BDh,015h,017h,035h
    att20:   db       03Eh,03Eh,05Ch,05Ch,05Eh,07Ch,07Ch,07Eh,09Dh,09Dh
    att30:   db       09Fh,0BDh,000h,000h,000h,002h,002h,002h,002h,003h
    att40:   db       021h,021h,021h,021h,021h,023h,023h,023h,023h,023h
    att50:   db       041h,041h,048h,048h,048h,04Ah,04Ah,04Ah,04Ah,068h
    att60:   db       068h,068h,068h,068h,068h,06Ah,06Bh,06Bh,06Bh,089h
    att70:   db       089h,089h,089h,08Bh,08Bh,08Bh,08Bh,0A9h,0A9h,0A9h
    att80:   db       0A4h,0A6h,0A6h,0A6h,0A6h,0C4h,0C4h,0C4h,0C4h,0C6h
    att90:   db       0C6h,0C6h,0C6h,0E4h,0E4h,0E5h,0E5h,0E7h,0E7h,0E7h
        END
    I'm looking to just read in the data adjust the hex values and then save the data in the exact form which I read it in. If read from spreadsheet file can not recognize multiple delimiters that is all I need to know. I do not want to spend time reading it in using a single delimitor and doing a bunch of string manipulation. I'm also working with LabView 8.5 if that makes a difference.

    You should use "scan string for tokens", and wire an array of delimiters.
    One nice behavior is the fact that consecutive delimiters are contracted into one (by default), so e.g. if your delimiters is an array containing a space and a comma, a sequence of three spaces and a comma would still count as one delimiter.
    For some ideas, have a look at my old example here:
    http://forums.ni.com/ni/board/message?board.id=170&message.id=192847#M192847
    LabVIEW Champion . Do more with less code and in less time .

  • Load text file with diff delimiters

    I need to load a text file that is pipe "|" delimited except for the last field that is not delimited by a pipe but with whitespace
    when executing the mapping the only place where I get a problem is on the last field
    "Field in data file exceeds maximum length"
    my initial thought was it not using TRAILING NULLCOLS but it is
    But looking at the code it generates the problem is obvious
    I write the code like this
    Options ( Errors = 50, Rows = 2000, BindSize = 90000)
    Load Data
    Infile 'file1.txt'
    Into Table "table_name" Truncate (
    field1               Char          Terminated by '|' ,
    field2               Integer External Terminated by '|' ,
    field3               Char          Terminated by '|' ,
    filed4               Decimal External Terminated by whitespace)
    warehouse builder writes it like this
    FIELDS
    TERMINATED BY '|'
    OPTIONALLY ENCLOSED BY '"'
    TRAILING NULLCOLS
    ( "field1 " POSITION (1) CHAR ,
    "field2" INTEGER EXTERNAL ,
    "field3" CHAR ,
    "field4" Decimal External
    these are two correct way of loading data
    how do I tell warehouse builder to load data where there are more than one termination charater

    s.split(delims) will return an array of strings, not a string. So you need to declare list as an array list of such arrays:ArrayList<String[]> list = new ArrayList<String[]>();(It's a good idea to copy and post compiler messages here, so no-one has to guess. Likewise indicate which line of your code they are referring to.)
    [Edit]If it only the contents of the array you wish to put in the array, then you can just say List list = Arrays.asList(s.split(delims));

  • Reading a text file with foreign language characters

    I'm trying to convert foreign language characters to English looking characters.  I have code that works, but only if I hard code the string with foreign language characters and pass it to the function. I cannot figure out how to get my program to read
    in the foreign characters from my file, they come in as garbage. 
    Since the function works when I pass a hard coded string to it, I'm pretty sure the problem is the way I have the Streamreader set up, it's just not reading the characters correctly...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader "m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with English characters
    Function removeAccent(ByVal myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    I know that removing the accent changes the meaning of the word, but this is what the user wants so it's what I need to do. 
    Any help is greatly appreciated!! :)
    Thanks!
    Joni

    Finally got it to work.  I had to remove the first 5 characters from the replacement string (ŠŽšžŸ), couldn't find encoding that would handle these, and to be honest, I didn't really need them.  The important ones are still there, was probably
    just overkill on my part.
    UTF7 worked for the rest...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader("m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter
    ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with english characters
    Function removeAccent(ByRef myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "AAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    Thanks for all your help!  Greatly appreciated :)
    -Joni

  • How to read/write text file to db2 by using java code

    Hai
    I created the table to insert a clob data as follows
    db2 => create table ctest(datas clob(65536))
    DB20000I The SQL command completed successfully.
    db2 => describe table ctest
    Column Type Type
    name schema name Length Scale Nulls
    DATAS SYSIBM CLOB 65536 0 Yes
    1 record(s) selected.
    I tried the following java code to insert a clob data.
    public static synchronized Connection getConnection() throws Exception {
    Connection m_connectionDatabase = null;
    try {
    Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
    // Get the connection to the database.
    m_connectionDatabase = DriverManager.getConnection(
    "jdbc b2 ps","","");
    }catch (Exception e) {
    throw new Exception("Failed to connect to the database. ", e);
    return m_connectionDatabase;
    public static void main(String a[]) {
    File file = new File("d:\\a.txt");
    InputStream fis = new FileInputStream(file);
    Connection con = getConnection();
    PreparedStatement pstmt = con.prepareStatement("insert into ctest values(?)");
    //try 1
    pstmt.setAsciiStream(1,fis,(int)file.length());
    // try 2
    pstmt.setCharacterStream(1,fis,(int)(file.length()));
    // try 3
    pstmt.setBinaryStream(1,fis,(int)(file.length()));
    // try 4
    byte[] b = new byte[fis.available()];
    fis.read(b);
    pstmt.setBytes(1, b);
    // try 5
    byte[] b = new byte[fis.available()];
    fis.read(b);
    pstmt.setString(1, new String(b));
    pstmt.executeUpdate();
    pstmt.close();
    fis.close();
    Result:
    If the file size is less than 32kb, it inserted successfully.
    but if more than 32kb, it throws follwing exception
    COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0352N An unsupported SQLTYPE was encountered in position "1" of the input list (SQLDA). SQLSTATE=56084
    at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
    at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.throw_SQLException(Unknown Source)
    at COM.ibm.db2.jdbc.app.SQLExceptionGenerator.check_return_code(Unknown Source)
    at COM.ibm.db2.jdbc.app.DB2PreparedStatement.loadParameters(Unknown Source)
    at COM.ibm.db2.jdbc.app.DB2PreparedStatement.execute2(Unknown Source)
    at COM.ibm.db2.jdbc.app.DB2PreparedStatement.executeUpdate(Unknown Source)
    Can any body please help out to insert clob value.
    Thanks in advance
    V.Shan

    Normally I would be happy to help you, but after several years of trying to help here, I've decided not to contribute anymore because of the piss-poor way in which this site is being administered.
    Others are still helping, but more may leave if things don't improve. May I recommend devshed or javaranch?
    http://www.devshed.com/
    http://www.javaranch.com/
    If you would like to complain to the admins of this forum, either click the "Report Abuse" link or the "Feedback" link.
    -- foofoo (shamelessly stolen the text from jverd).

  • How to read text file with big5 into db

    hi,
    how can i use UTL_FILE package to
    read a text file with big5 characters and insert into db?
    my oracle charset is AL32UTF8.
    thx a lot!

    Thx for yr answer!!!
    I have followed and it works.
    However, I got another problem with HKSCS. When the text file contained HKSCS, the store procedure also treats it as Big5 and when I select it out, the character was not the orginal one.
    Please suggest if you have any ideas.
    Many Thanks!!!

  • Quick look for text files with non-registered extensions

    It seems there was a way in 10.5 and 10.6 to register certain extensions with Quick Look to tell them how to preview a file. I have a lot of plain text files with different extensions that are not initially recognized by Quick Look. How do I hack the registry to tell Quick Look to preview a .cfg (or .aux, etc.) file as plain text?

    Can't Quick Look for some text files
    Re: Is it possible to change the viewing format?
    Quick Look for files without extensions.
    Re: Can I view text files without a .txt extension in Quick Look?
    How do I add support to Quick Look

  • How to open saved files using 'read from text file' function

    Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
    Here are some screenshots on part of my program  
    let me know if you guys would need more information / screenshots thank you!
    Attachments:
    ss_save.jpg ‏94 KB
    ss_open.jpg ‏94 KB
    modified_writetotextfile.jpg ‏99 KB

    Ohmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
    ( ps . cant connect it now unless my program is working otherwise labview will crash ) 
    ( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
    The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
    Attachments:
    frequency detactor.vi ‏53 KB
    signal generator.vi ‏13 KB
    attachment.ashx.vi ‏40 KB

  • Reading dilimited input from a text file with tokenizer

    i am trying to read in a text file with the following structure: 2 integers on each line with comma as the delimitor.
    i am using the BufferedReader stream and Tokenizer to detect ",".
    try {
    BufferedReader in = new BufferedReader(new FileReader(filename));
    //read in the data file
    while ((s = in.readLine())!= null) {
    int i = 0;
    for (i = 0; i < 100; i++) {
    t = new StringTokenizer(s,",");
    A1 = Integer.parseInt(t.nextToken());
    catch (IOException e) {System.err.println(e);}
    When i print out A1[i], it only reads the last line of the text file. Please tell me what's wrong.
    Also i'd really like A1[i] to store the integer before the comma and another array A2[i] to store the integer after the comma. Please help.
    Thanks.
    p.s. A1 and A2 are arrays...when i previewd message in Netscape 7 it left out the brackets and the index....

    What is the for i loop for? If it is to read the next line from the file, then the while loop has taken care of it. Other than this there should be no problem with the rest of the code.
    Just add another line to store the next token into A2.

  • I would like to read a text file in which the decimal numbers are using dots instead of commas. Is there a way of converting this in labVIEW, or how can I get the program to enterpret the figures in the correct way?

    The program doest enterpret my figures from the text file in the correct way since the numbers contain dots instead of commas. Is there a way to fix this in labVIEW, or do I have to change the files before reading them in the program? Thanks beforehend!

    You must go in the labview option menu, you can select 'use the local
    separator' in the front side submenu (LV6i).
    If you use the "From Exponential/Fract/Eng" vi, you are able to select this
    opton (with a boolean) without changing the labview parameters.
    (sorry for my english)
    Lange Jerome
    FRANCE
    "Nina" a ecrit dans le message news:
    [email protected]..
    > I would like to read a text file in which the decimal numbers are
    > using dots instead of commas. Is there a way of converting this in
    > labVIEW, or how can I get the program to enterpret the figures in the
    > correct way?
    >
    > The program doest enterpret my figures from the text file in the
    > correct way since the numbers contain dots instea
    d of commas. Is there
    > a way to fix this in labVIEW, or do I have to change the files before
    > reading them in the program? Thanks beforehend!

  • How to read a text file using Java

    Guys,
    Good day!
    Please help me how to read a text file using Java and create/convert that text file into XML.
    Thanks and God Bless.
    Regards,
    I-Talk

         public void fileRead(){
                 File aFile =new File("myFile.txt");
             BufferedReader input = null;
             try {
               input = new BufferedReader( new FileReader(aFile) );
               String line = null;
               while (( line = input.readLine()) != null){
             catch (FileNotFoundException ex) {
               ex.printStackTrace();
             catch (IOException ex){
               ex.printStackTrace();
         }This code is to read a text file. But there is no such thing that will convert your text file to xml file. You have to have a defined XML format. Then you can read your data from text files and insert them inside your xml text. Or you may like to read xml tags from text files and insert your own data. The file format of .txt and .xml is far too different.
    cheers
    Mohammed Jubaer Arif.

Maybe you are looking for

  • On a wireless network test report, I get "The wireless radio is not functioning."

    The printer is a Photosmart C309a all-in-one.  I've used this printer for some time and did so wirelessly earlier today.  Upon ordering a print job the printer failed to produce results.  I ran a Network Configuration Page where it showed the printer

  • Can't boot Arch from external HDD

    Hi, well first off this is not my first Arch Linux installation, I'm using Arch for a little over a year now (coming from slack). But this is my first attempt to have Arch on an external HDD. Alrighty, the situation is as follows: A rather new comput

  • Business Partner in EBP gets centrally blocked.

    Hi,      I have noticed the business partner for a user in EBP gets centrally blocked, and this happens automatically.  So the user gets this error " Partner is blocked " while creating shopping carts. This problem gets solved when we unblock the par

  • "ORA-00904: "POLTYP": invalid identifier" in export

    First I got errors when I did the export with an export tool of Release 11.1.0.7.0 and there were lot of ORA-00904 and ORA-01003 like the following: XP-00008: ORACLE error 904 encountered ORA-00904: "MAXSIZE": invalid identifier . . exporting table X

  • My Muse compositions, panels and slideshows dosen't work (preview).

    Hi! What's wrong? I didn't have any problems with muse earlier... older version and older Win XP. Now I have the latest version of Muse and Win8. My compositions, panels and slideshows dosen't work when I try to preview designt site in browser. Is so