Read file line by line

Hi
Could somebody tell me how to read file line by line ? Namely my input file I want to read look as follow:
AAA 1, 1
12 222 12
AAA 2, 2
11 122 11
My output file should look as follow:
1, 1, 12
1, 1 222
1, 1, 12
2, 2, 11
2, 2, 122
2, 2, 11
I think the lines need to be stored in ArrayList, then I would like those lines to write to csv file, but how on read I can construct such output file? This is my code for reading file
public ArrayList readFile(String filename)
  try
     BufferedReader in = new BufferedReader(new FileReader(filename));
     ArrayList list = new ArrayList();
     String lineS = null;
     while (in.ready())
      if ((lineS = in.readLine()).startsWith("")){
        String[] line = in.readLine().trim().split("\\s+");
        list.add(Integer.valueOf(line[0]));
        list.add(Integer.valueOf(line[1]));
        list.add(Integer.valueOf(line[2]));
     in.close();
     return list;
     catch (Exception e)
   e.printStackTrace();
return null;
Thanks

The rules for the conversion from input to the desired output are:
1. For each of the line with string take 2 integers for example 1, 1  from AAA 1, 1
2. Then repeat 1, 1 for each next number not containing any string, so if the line after AAA, 1, 1 has 12, 222, 12 then the output will look as follow
1, 1, 12
1, 1 222
1, 1, 12
3. Repeat the process (the pattern is the same 1 line with string 1 line with numbers)
Actually I am not sure how to perform that logic for such conversion as for now I am only able to list only the numbers but I have a problem to add numbers from the line having string in it.
STOP!
You should NOT be writing code if you are 'not sure how to perform that logic'.
You are getting ahead of yourself.
There is NOTHING to gain by trying to code a solution before you know what algorothm you need. Big mistake.
Should I use list or maybe if the patter for lines is the same array will be more sufficient?
NEITHER ONE!
Those are 'solutions' used to implelment an algorothm.
You do NOT yet know what algorithm you need to use so how can you possibly write code to implement the unknown?
How to perform logic to get the numbers from line having string and for the next lines having only numbers in order to structure it into desired output? 
THAT is the question your thread subject should have.
Until you get the answer to it don't write any code,.
Do NOT try to automate what you can't do manually.
Write down, on paper or use an editor, the step by step 'logic' you need and walk through that logic from beginning to end until the 'logic' works and produces the correct result.
You just now have started to do that when you listed those rules above.
But you left some things out. Expand on that list of 'rules' and provide a little more example data. TPD has given you a good example. Reread what they said.
Did you notice they start by talking about 'tasks': what each task does and the order the tasks need to be performed.
That 'task list' has NOTHING to do with Java, C, or any other language: it is identifying the problem/algorithm. Until you have that coding is premature.

Similar Messages

  • Text file: reading char one at a time line by line

    I need to read an external .txt file, one character at a time, line by line, and compare each character in order to do various things. The problem is that when I use the Buffered Reader I have only readLine() method and others to work with, but none that actually read a character at a time, and line by line. The program has to read a character, then move to the next one and read it, and so on. Then move to the next line, and read the first character, and so on. I am working with chars not Strings. Could you please help me with this problem?

    InputStreamReader can read a single char.
    InputStreamReader isr = new InputStreamReader(InputStream in);
    isr.read(); will return 1 character from "in".

  • I want to read the contents of a file to a text item line by line dynamical

    I have created a timer
    tm_id := FIND_TIMER('LOG_READING_TIMER');
    If Id_Null(tm_id)
    then
    tm_id := create_timer('LOG_READING_TIMER', 1000, REPEAT);
    else
    set_timer (tm_id, 1000, REPEAT);
    end if;
    /* executed the shell script on application server */
    host(v_command,no_screen);
    and used below code for reading a file in when timer expired
    DECLARE
    v_file_name := '/home/log.txt' /* log created during running shell script */
    BEGIN
    v_infile := Text_IO.Fopen(v_file_name , 'r');
    loop
    Text_IO.Get_Line(v_infile,v_linebuf);
    :CONTROL.item:= :CONTROL.item||v_linebuf||chr(10);
    end loop;           
    WHEN no_data_found THEN
         Text_IO.Fclose(v_infile);
         delete_timer('LOG_TIMER');
    END
    I want to read a log file which is created while runnning shell script line by line
    dynamically
    Above code is reading the log filebut all the lines are shown at once.
    I have to display
    each line on the text item
    and the next line line by line
    Can anyone help me how to achieve this.
    Thanks,
    in advance

    In when-button-pressed trigger
    I have called a shell script on application server using host command
    HOST('Path of script',NO_SCREEN);
    Shell script writes some set of statements to log file on application server
    Problem is to read the log file on to the multiline text item each line simultaneosly
    while running the script.
    Below is the procedure i have written to achieve this but below code is writing all the lines at once
    after entire complete execution of shell script.
    for example
    shell script writes tolog file:
    1. 'Loading of tables';
    then loads the data
    2. 'emailing data';
    3. ...
    4. ...
    Below code writes
    all the 4 lines at once
    I want to see in frontend what is going on while running the script
    by reading the log file data line by line
    WHEN-BUTTON-PRESSED
    tm_id := FIND_TIMER('LOG_READING_TIMER');
    If Id_Null(tm_id)
    then
    tm_id := create_timer('LOG_READING_TIMER', 1000, REPEAT);
    else
    set_timer (tm_id, 1000, REPEAT);
    end if;
    /* executed the shell script on application server */
    host(v_command,no_screen);
    WHEN-TIMER-EXPIRED
    and used below code for reading a file in when timer expired
    DECLARE
    v_file_name := '/home/log.txt' /* log created during running shell script */
    BEGIN
    v_infile := Text_IO.Fopen(v_file_name , 'r');
    loop
    Text_IO.Get_Line(v_infile,v_linebuf);
    :CONTROL.item:= :CONTROL.item||v_linebuf||chr(10);
    end loop;
    WHEN no_data_found THEN
    Text_IO.Fclose(v_infile);
    delete_timer('LOG_TIMER');
    END
    While running the script on application server
    I want to see the data from log file simulataneously on to the form when the data is written on to the log file
    Please let me know if you need more details.
    Thanks,
    in advance

  • Adobe Reader 11 (XI) won't open file via command line

    Hello,
    I have posted this question to probably inapropriate topic earlier today, so I am repeating it again.
    I installed newest Adobe Reader XI today and when I tried to open certain pdf file via command line, it reported a syntax error. Now, this syntax worked so far on versions 9 and 10  (I checked today with them and it is working), so my question is - where can I find new syntax, if there is any? Googling didn't help. Or what else could wrong?
    In previous versions I was able to open pdf file (on page 5) like this (all was taken from Help file "Open parameters")
    "CompletePathToAdobeReader"/A"page=5""CompletePathToPDF",
    ie
    "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe"/A"page=5""d:\V2\DataSheet.pdf"
    but now - not that it doesn't open specific page, but it doesn't want to open file at all.
    edit:
    Operating systems running: Windows 7, Windows XP
    Thank you.
    Message was edited by: v604

    Yes, it reported correctly becuase there is a syntax error in your command. Try spaces between the /A switch and open parameter. Try this:
    "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /A "page=5" "d:\V2\DataSheet.pdf"
    Hope this helps.
    -Sumit

  • How to read from a file line by line

    Hi
    I am new to using LabView and was wondering how I could read data from a text file one line at a time and display this data one line at a time as well. I tried looking through the Reading from Text File . vi example but that just seems to be reading and displaying everything together.
    Thanks
    -Karan

    Hi
    My aim is to read text line by line and to then go ahead and display the last 8 reaad lines of code to give the impression of text falling down a screen. I tested the first while loop and that seemed to work fine. However, when I encounter an EOF, I would like the text already read to keep making its way down the screen and keep inputting NULL characters into the array to simulate the effect of the text falling down the screen which is why I created the second while loop. I tried to input the NULL characters using a box for ENUM constants. However, I kept getting an error saying the data types do not match. What would I need to do? For the display I plan on putting indicators next to the 8 places where the text would be stored which I have not done so far.
    I am also attaching a copy of the error.
    Thanks
    -Karan
    Attachments:
    DisplayText.vi ‏40 KB
    Error.JPG ‏89 KB
    PictureOfBlock.JPG ‏120 KB

  • How to read a file line by line in UTL

    Hi All,
    DECLARE
    fileID UTL_FILE.FILE_TYPE;
    strbuffer VARCHAR2(100);
    BEGIN
    fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
    UTL_FILE.GET_LINE (fileID, strbuffer);
    dbms_output.put_line(strbuffer);
    END;
    By this program I can read only first line of the file. I want to read the file line by line.
    Thanks
    Sunil

    try this
      DECLARE
        fileID UTL_FILE.FILE_TYPE;
        strbuffer VARCHAR2(100);
      BEGIN
        fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
        if utl_file.is_open(fileID) THEN
          loop
            UTL_FILE.GET_LINE (fileID, strbuffer);
            dbms_output.put_line(strbuffer);
            if strbuffer IS NULL THEN
              exit;
            end if;
          end loop;
        end if;
      END;note: untested.

  • How do I read a text file line by line and store to array

    I have a text file, I want to be able to store each line of the file in an array, how would I go about doing this? code example? tutorial? Thank you

    Well, you got the pseudo code:
    a) read line
    b) add to array
    So whats the problem? What don't you know how to do?
    What does your text book tell you about reading files. I'm sure it has an example, every book I've read does.
    By the way I would use an ArrayList to store each line of text, that way you don't need to know in advance.

  • Read at each new line from .txt file

    Hi guys
    I want to read from a file which I am saving using labview. What I am doing is reading 128 bytes fro VISA port and saving it in .txt file with new line constant. At some later time I want to read 128 bytes from that text file do some processing and display it. The "read from text file" vi has convert EOL but I am not able to configure it. Please help me..
    Thanks in advance
    Niladri

    Hi Newbee_3,
                                                  Do 1 thing, Read the txt file & convert this into string, Then you have all the flexibility to do whatever you want.
    Thanks
    Kudos are always welcome if you got solution to some extent.
    I need my difficulties because they are necessary to enjoy my success.
    --Ranjeet

  • Please how can i read file, to find number of lines and to extract number of block data, and number of data in each block

    please if you can give me an example

    I attach a file wich i want read:
    1- to know a number of lines in file
    2- from the second line of the file to the line befor NCOUNT, put the lines in array like this, Variable and values like this Ex: TIMET 1 0 1 ..... first line
    and put the values of NCOUNT in array
    I attach a file
    Attachments:
    karim1.txt ‏2 KB
    Read_Filenew.vi ‏29 KB

  • Read an ascii file line by line

    I am new with CVI, and I need to read an ascii file with multiple lines in the following format:
    at_test_2_to_13=0.861000
    at_testabcd_9_to_21=0.712000
    at_abdgx_5_to_8=0.892000
    here is the code for writing in the ascii file:
    sprintf(ctResult, "%s=%f\n", TestName1,result1);
    WriteFile (fileHdl,ctResult ,StringLength(ctResult) );
    At a later time, I need to read the text file, find the test name (for example "at_testabcd_9_to_21") and record the value after the "=" sign (in this case 0.712000). The number of lines in the text file is not fixed.
    I am writing the data to the file with no problems, but I am stack in reading the data.
    I would appreciate any help on how to write this code in CVI.
    Thank you in advance
    Solved!
    Go to Solution.

    As Wolfgang already proposed, you can use the ini-file library.
    With this library, you can write the results in a structured manner and access an individual measurement by its name, without the need of reading every line above.
    I also attached a sample project for what you asked.
    Check the ini-file library help and samples for the other option.
    S. Eren BALCI
    www.aselsan.com.tr
    Attachments:
    AsciiRead.zip ‏2 KB

  • Powershell read CSV file line by line and only first header

    I have a CSV file, which reads like this:
    read, book
    read1, book1
    read2, book2
    I want to read only the first value, before comma one line at time,
    meaning first time it will be
    read
    read1
    read2
    no headers and i want to pass that value to a variable for a if condition.
    I have script it read line by line but it reads both values before coma and after line by line, so instead of having three values i'm ending with 6 values.
    $file = Import-CSV c:\script\server.csv
    $file | ForEach-Object {
            foreach ($property in $_.PSObject.Properties) 
    $property.Name
    $property.Value
    #replace = $property.Value

    If you can work with headers then do so as it will make your life easier.
    with a csv file called server.csv like this:
    headername1, headername2
    read, book
    read1, book1,
    read2, book2
    and this bit of code 
    $file = Import-CSV c:\script\server.csv
    #output to host, file or directly pipe the command above.
    foreach($cell in $file.headername1){ if($cell -eq $something){ }}
    will evaluate the content of each cell to $something.
    This is because Powershell will grab the first row and claim that as a header name.
    So whatever you put in cell A1 in excell will end up as name of the first collumn and its corresponding property (e.g. $file.A1 oor $file.headername1 if you will).

  • What is the best way to read a file line by line?

    Hello, everyone!
    I want to read a file line by line, i.e. each time, a line of a text file is read and stored as a String object and the String object will be manipulated (parsed) later.
    I have found that FileInputStream does not have a function which is responsible for reading a line each time from a text file. Anyone have good suggestions?
    Best regards,
    George

    I always use the following example.. mayb that would help you as well
    File fid = new File(fileName);
    if (fid.exists())
            fr = new FileReader(fid);
            br = new BufferedReader(fr);
             while((txtstr= br.readLine()) != null)
    }

  • Read the file line by line from upload

    Hi Guys,
    Need help... I creating a web application that has a upload capability. What I want to do is this...
    I want to upload a file (but not save it). What I'm going to do is just read the file line by line and save these data to the database. How can I do this? (BTW, I'm using struts (FormFile)).
    Please guide me please!
    Thanks.

    i think u should obtain a inputstream from request object and then save it to the database using BLOB object.

  • Read a specific line of a txt file using vba not using line by line, Leer una Linea especifica de archivo de texto sin recorrer linea por linea

    Buenos días - Good morning
    Mi pregunta la escribiré en español y en ingles y espero alguien tenga la solución.
    I'll write my question in Spanish and English and I hope someone has the solution.
    SPANISH
    Creé una Macro en VBA que lee mas de 200.000 archivos de texto (.txt) los cuales tienen diferentes tamaños y cantidad de información dentro de ellos, de cada archivo necesito extraer la información de las 3 primeras lineas y las ultimas 10 lineas, las 3
    primeras lineas es fácil ya que uso un "READLINE" 3 veces y voy capturando la información de las tres primeras lineas, para las ultimas 10 lineas las cuales están identificadas por un código inicial hago un ciclo que lee linea por linea hasta que
    encuentra el numero 3 en un espacio especificado de la linea y de ahí captura la información de cada linea de texto que serian las 10 ultimas, el problema que tengo es que la cantidad de archivos y de información dentro de los archivos aumenta considerablemente
    cada día y por tener el ciclo que lee cada una de las lineas de cada archivo de texto la Macro se demora cada vez mas a medida que aumenta la información y consume cada vez mas memoria de la maquina.
    Necesito un método diferente que no lea linea por linea y que yo le pueda decir lea la linea (renglón) numero 1000 (ejemplo) y capture la información a partir de ahí para ahorrar algo de tiempo, o saber cuantas lineas de texto tiene el archivo .txt y decirle
    que me lea a partir de (numero total de lineas del txt -(menos) 10 lineas) así me leería las 10 ultimas.
    ENGLISH
    I created a Macro in VBA that reads more than 200,000 text files (.txt) which have different sizes and quantity of information within them, each file need to extract the information from the first 3 lines and last 10 lines, 3 first lines is easy as using a
    'READLINE "3 times and am capturing information from the first three lines, for the last 10 lines which are identified by an initial code I make a loop that reads line by line until it finds the number 3 in a specified area of ​​the line and then capture
    the information of each line of text that would be 10 last, the problem that I have is that the number of files and information within files significantly increases every day and having the loop that reads each line of each text file is delayed Macro increasingly
    as more information and consume more and more memory on the machine.
    I Need a different method not read line by line and I can tell you read the line (row) number 1000 (example) and capture the information from there to save some time or know how many lines of text have the file .txt and tell me read from (total number of lines
    of txt - (minus) 10 lines) so I would read 10 last.
    Here is the code I currently use
    Dejo el código que uso actualmente
    Dim fs, f, ts, REG
    Set fso = CreateObject("Scripting.FileSystemObject")
        On Error Resume Next
    sFilePath = strFolder & "\" & strFileName
    Set f = fso.getFile(sFilePath)
    Set ts = f.OpenAsTextStream(1, 0)
    REG = ts.READLINE
    Ciclo para llegar hasta las ultimas 10 lineas
    Cycle to reach the last 10 lines
    For J = 1 To 200000
                REG = ts.READLINE
                    If Val(Mid(REG, 6, 1)) = 3 Then

    Good Morning ryguy72
    First thank you so much for your answer, sorry for my english in the question, I tried for a long time to make a code that wasn't so slow to read the last 10 lines, 'cuz most codes used a cycle "For" to read line by line asking if in the specific
    position is the character(number) that tells me that i should get started to read the last lines that i need, that takes a lot longer than your code doing a Split with Mydata and storing it in strData(). I don't know how to do this and every forum that
    i consulted to read the last 10 lines quickly they made the same read line by line with a Cycle "for".
    Thanks again, I gonna improve my code with your help, 'cuz it took about 4 hours to read all the information and everyday ascended more time and memory consumption.
    Thanks to everyone who offered their help so disinterested and free, so should always be people with that spirit, I hope someday to be SO good as you programming.

  • File Reader that can read line by line contents

    Hi there!
    I would like to ask how to read the content of a file line by line... I need to convert all the contents of a text file into html file.
    Example:
    3890001604AM0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.
    3890003011NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.
    3890003012NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.
    3890003014NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.
    I need to insert <BR> tag after the last character of every line or enclose each line with <LI></LI> tag.
    Result
    3890001604AM0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.<BR>
    3890003011NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.<BR>
    3890003012NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.<BR>
    3890003014NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.<BR>
    OR
    <LI>3890001604AM0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.</LI>
    <LI>3890003011NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.</LI>
    <LI>3890003012NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.</LI>
    <LI>3890003014NZ0 - With Shipping Order DT Actual Transactions ... Joji to provide GMUS.</LI>
    How can I do this in java? I am currently using the FileReader class but It seemed that it reads character by character and I am having a hard time in inserting the <BR> tag or enclosing each line with <LI> and </LI> tags.
    Anyone who got some ideas in dealing with this problem?
    Thank you and God bless.

    BufferedReader in = new BufferedReader(new FileReader("..."));
    String line = null;
    while ((line = in.readLine()) != null) {
      /* use line */
    // close reader

Maybe you are looking for

  • IPod Mini cannot be updated by iTunes on a Mac

    OK, I'm confused. I plugged my iPod mini into my PM G5 (10.4.7, iTunes 7) to update some songs I bought. I got a message telling me the iPod needed to be updated. OK, tried that...I get a "the computer can not communicate with the iPod Error Code 141

  • Deleted podcasts, now getting constant sync errors

    Apparently I deleted a podcast (maybe unsubscribed?) a while back and now everytime I sync my iPod, I get the error +"Some of the items in the iTunes library, including "...", were not copied to the iPod "..." because they could not be found."+ I und

  • Safari 6 Continuously Crashing

    After upgrading to Mountain Lion, Safari 6 is extremly unstable. It crashes often and once it crashes it will crash everytime you try to reopen the app. The only solution seems to be to switch to another browser for a while and after a while Safari i

  • Sending PDF with a certain character type

    Hi all, 1. After getting the print parameters with the function u2018GET_PRINT_PARAMETERS' CALL FUNCTION 'GET_PRINT_PARAMETERS' EXPORTING DESTINATION = 'N006' *LINE_SIZE = 080 line_count     = 65 IMMEDIATELY = ' ' NO_DIALOG = 'X' IMPORTING OUT_PARAME

  • Update essbase variables with OS date

    Hi All, Is there a way to update my substitution variables according to the Operating System date? I am trying to avoid some manual process involved in maintaining the application. I am looking for any solutions out of Hyperion. Any help is appriciat