How to read from a text file one character at a time?

Hello
I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
can anyone help me?
Lavi 

lava wrote:
I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
can anyone help me?
Some additional comments:
You really don't want to read any file one character at a time, because it is highly inefficient. More typically, you read the entire file into memory with one operation (or at least a large chunk, if the file is gigantic) and then do the rest of the operations in memory.  One easy way to analyze it one byte at a time would be to use "string to byte array" and then autoindex into a FOR loop, for example.
Of course you could also read the file directly as a U8 array instead of a string.
Message Edited by altenbach on 06-10-2008 08:57 AM
LabVIEW Champion . Do more with less code and in less time .

Similar Messages

  • Read data from a text file, one line at a time.

    I need to read data from a text file, and display each line in a String Indicator on Front Panel. It displays each line, but I get Error 4, End Of Line, unless I enter an extra line of data in the file that I don't need. I tried Read From Text File.vi, made by Nat Instr, and it gave the same error.

    The Read from Text File.vi reads data from a text file line by line until the user stops the VI manually with the Stop button on the front panel, or until an error (such as "Error 4, End of file") occurs. If an error occurs, the Simple Error Handler.vi pops up a dialog that tells you which error occurred.
    The Read from Text File.vi uses a while loop, but if you knew how many lines you wanted to read, you could replace the while loop with a for loop set to read that many lines from the file.
    If you need something more dynamic because the number of lines in your files vary, then you could change the code of the Read from Text File.vi to the expect "Error 4, End of file" and handle it appropriately. This would require unbundling the error cluster that comes fro
    m the Read File function with the Unbundle By Name function, so that you can expose the individual error "status" and error "code" values stored in the cluster. If the value of the error "code" is 4, then you can change the error "status" from true to false, and you can rebundle the cluster with the Bundle by Name function. Setting the error "status" to false instructs the Simple Error Handler to ignore the error. Otherwise, pass the original error cluster to the Simple Error Handler.vi, so that you can see what the error is.
    Of course, if you're not interested in what the errors are, you could just remove the Simple Error Handler.vi, but then you wouldn't see any error messages.
    Best of Luck,
    Dieter
    Dieter Schweiss
    Applications Engineer
    National Instruments

  • HOW TO WRITE AND READ FROM A TEXT FILE???

    How can I read from a text file and then display the contents in a JTextArea??????
    Also how can I write the contents of a JTextArea to a text file.
    Extra Question::::::: Is it possible to write records to a text file. If you have not idea what I am talking about then ignore it.
    Manny thanks,
    your help is much appreciated though you don't know it!

    Do 3 things.
    -- Look through the API at the java.io package.
    -- Search previous posts for "read write from text file"
    -- Search java.sun.com for information on the java.io package.
    That should clear just about everything up. If you have more specific problems, feel free to come back and post them.

  • How to read a whole text file into a pl/sql variable?

    Hi, I need to read an entire text file--which actually contains an email message extracted from a content management system-- into a variable in a pl/sql package, so I can insert some information from the database and then send the email. I want to read the whole text file in one shot, not just one line at a time. Shoud I use Utl_File.Get_Raw or is there another more appropriate way to do this?

    how to read a whole text file into a pl/sql variable?
    your_clob_variable := dbms_xslprocessor.read2clob('YOUR_DIRECTORY','YOUR_FILE');
    ....

  • Reading from a text file into a 2D array

    How do you read from a text file and put it into a 2D array? Or if someone could guide me to where I can find the information?

    This tutorial shows how to read a file:
    http://java.sun.com/docs/books/tutorial/essential/io/scanfor.html
    This tutorial shows how to create arrays with multiple dimensions:
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html

  • Getting repeated values when reading from a text file.

    I need to read from a text file. When the token encounters a particular word (command) I need to read the next line and perform some actions. However, this part is working but it is repeating the values again and again until it encounters the next particular word (command). Hope that someone will help me out, as always when I posted a problem in these forums.
    SetOperations class - contains the set methods
    // Imported packages.========================================================
    import java.util.Vector;
    import java.util.Iterator;
    // Public class SetOperations.===============================================
    public class SetOperations
         // Instance variables.===================================================
         private Vector v = null; // Creates new instance of vector.
         protected int memberCount;
         // Constructor.==========================================================
         public SetOperations()
              v = new Vector();
         } // end constructor.
         // Method isMember.======================================================
         * Checks whether the element is already a member of the set.
         * @return True if Vector v contains Object member.
         public boolean isMember(Object member)
              if (member != null) // only if Object member is not null.
                   return v.contains(member); // returns true if vector already contains member.
              else
                   return false; // returns false if vector does not contain member.
         } // end public boolean isMember(Object member).
         // Method addMember.=====================================================
         * Adds a member to the set.
         * @return Adds Object member to Vector v.
         public void addMember(Object member)
              //if (! v.contains(member)) // only if element is not already a member.
              if (isMember(member) == false) // only if element is not already a member.
                   v.add(member); // adds a member.
         } // end public void addMember(Object member).
         // Method countMember.===================================================
         * Returns the number of members present in the vector.
         * @return Number of elements present in the vector.
         public int countMember()
              return v.size();
         } // end public int countMember().
         // Method isSetEmpty.====================================================
         * Returns true if set is empty.
         * @return True if no elements are present in Vector v.
         public boolean isSetEmpty()
              return v.size() == 0; // returns 0 if no elements are present in the vector.
         } // end of public boolean isSetEmpty().
         // Method printMember.===================================================
         * Displays member/s of the set.
         * @return Prints element/s present in the vector.
         public void printMember()
              for (int i = 0; i < v.size(); i++) // iterates through present members.
                   System.out.println("[" + i + "] " + v.get(i)); // displays member/s present in the vector.
         } // end of public void printMember().
    } // end public class SetOperations.
    SetTextLauncher class - reads from a text file and implements the set operations
    // Imported packages.========================================================
    import java.util.*;
    import java.io.*;
    // Public class SetTestLauncher.=============================================
    public class SetTestLauncher
         // Main method public static void main(String args[]).===================
         public static void main(String args[])
              displayFile("test.txt"); // outputs result from text file.
         // method to display a file on screen
         public static void displayFile (String textFile)
              // Instance variables.===============================================
              // Creates new instances of SetOperations.
              SetOperations setA = new SetOperations();
              SetOperations setB = new SetOperations();
              SetOperations setC = new SetOperations();
              SetOperations setD = new SetOperations();
              SetOperations setE = new SetOperations();
              // Initialisation.
              String line = "", nextLine = "";
              FileReader fr = null;
              try
                   // Opens the file with the FileReader data sink stream.
                   fr = new FileReader(textFile);
                   // Converts the FileReader input stream with the BufferedReader processing stream.
                   BufferedReader br = new BufferedReader(fr);
                   // Iterates through text file reading lines until end of text lines.
                   while (line != null)
                        line = br.readLine(); // reads one line at a time.
                        if(line == null) break; // when the line is null break the loop.
                        // Creates a new instace of StringTokenizer.
                        StringTokenizer st = new StringTokenizer(line);
                        // Loops until there are no more tokens.
                        while (st.hasMoreTokens())
                             String token = st.nextToken(); // reads next token.
                             // Only if the token encounters the String "membera".
                             if(token.equals("membera"))
                                  nextLine = br.readLine(); // gets next line.
                                  setA.addMember(nextLine); // adds a member to the set.
                                  // Displays members present in the set if vector is not empty.
                                  if (! setA.isSetEmpty())
                                       setA.printMember(); // print members present.
                                  // Displays the number of member/s present in the vector.
                                  System.out.println("Number of set members: " + setA.countMember());
              // Catches and displays exceptions.
              catch (FileNotFoundException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              catch (IOException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              finally
                   try
                        // if file is found
                        if (fr != null)
                             // close file
                             fr.close();
                   catch (IOException exp)
                        exp.printStackTrace();
         } // end public static void main(String args[]).
    } // end public class SetTestLauncher.

    Thanks for your interest. Please ignore SetOperations class, it is just the class containing the methods and it works correctly since I checked it without reading from a text file. I marked the part where I think lies my problem in class SetTestOperations.
    The information in the text file is as follows:
    membera
    Hillman
    membera
    Skoda
    membera
    Honda
    membera
    Toyota
    and the result is:
    [0] Hillman
    Number of set members: 1
    [0] Hillman
    [1] Skoda
    Number of set members: 2
    [0] Hillman
    [1] Skoda
    [2] Honda
    Number of set members: 3
    [0] Hillman
    [1] Skoda
    [2] Honda
    [3] Toyota
    Number of set members: 4
    instead of just one set:
    [0] Hillman
    [1] Skoda
    [2] Honda
    [3] Toyota
    Number of set members: 4
    Hope it is easier to understand like this.
    Regards
    Marco
    I need to read from a text file. When the token
    encounters a particular word (command) I need to read
    the next line and perform some actions. However, this
    part is working but it is repeating the values again
    and again until it encounters the next particular
    word (command). Hope that someone will help me out,
    as always when I posted a problem in these forums.
    SetOperations class - contains the set
    methods
    // Imported
    packages.=============================================
    ===========
    import java.util.Vector;
    import java.util.Iterator;
    // Public class
    SetOperations.========================================
    =======
    public class SetOperations
    // Instance
    e
    variables.============================================
    =======
    private Vector v = null; // Creates new instance of
    f vector.
         protected int memberCount;
    Constructor.==========================================
    ================
         public SetOperations()
              v = new Vector();
         } // end constructor.
    // Method
    d
    isMember.=============================================
    =========
    * Checks whether the element is already a member of
    f the set.
         * @return True if Vector v contains Object member.
         public boolean isMember(Object member)
    if (member != null) // only if Object member is not
    ot null.
    return v.contains(member); // returns true if
    if vector already contains member.
              else
    return false; // returns false if vector does not
    not contain member.
         } // end public boolean isMember(Object member).
    // Method
    d
    addMember.============================================
    =========
         * Adds a member to the set.
         * @return Adds Object member to Vector v.
         public void addMember(Object member)
    //if (! v.contains(member)) // only if element is
    is not already a member.
    if (isMember(member) == false) // only if element
    nt is not already a member.
                   v.add(member); // adds a member.
         } // end public void addMember(Object member).
    // Method
    d
    countMember.==========================================
    =========
    * Returns the number of members present in the
    e vector.
         * @return Number of elements present in the vector.
         public int countMember()
              return v.size();
         } // end public int countMember().
    // Method
    d
    isSetEmpty.===========================================
    =========
         * Returns true if set is empty.
    * @return True if no elements are present in Vector
    r v.
         public boolean isSetEmpty()
    return v.size() == 0; // returns 0 if no elements
    ts are present in the vector.
         } // end of public boolean isSetEmpty().
    // Method
    d
    printMember.==========================================
    =========
         * Displays member/s of the set.
         * @return Prints element/s present in the vector.
         public void printMember()
    for (int i = 0; i < v.size(); i++) // iterates
    es through present members.
    System.out.println("[" + i + "] " + v.get(i)); //
    // displays member/s present in the vector.
         } // end of public void printMember().
    } // end public class SetOperations.
    SetTextLauncher class - reads from a text file
    and implements the set operations
    // Imported
    packages.=============================================
    ===========
    import java.util.*;
    import java.io.*;
    // Public class
    SetTestLauncher.======================================
    =======
    public class SetTestLauncher
    // Main method public static void main(String
    g args[]).===================
         public static void main(String args[])
    displayFile("test.txt"); // outputs result from
    om text file.
         // method to display a file on screen
         public static void displayFile (String textFile)
    // Instance
    ce
    variables.============================================
    ===
              // Creates new instances of SetOperations.
              SetOperations setA = new SetOperations();
              // Initialisation.
              String line = "", nextLine = "";
              FileReader fr = null;
              try
    // Opens the file with the FileReader data sink
    ink stream.
                   fr = new FileReader(textFile);
    // Converts the FileReader input stream with the
    the BufferedReader processing stream.
                   BufferedReader br = new BufferedReader(fr);
    // Iterates through text file reading lines until
    til end of text lines.
                   while (line != null)
    line = br.readLine(); // reads one line at a
    at a time.
    if(line == null) break; // when the line is null
    null break the loop.
                        // Creates a new instace of StringTokenizer.
                        StringTokenizer st = new StringTokenizer(line);
                        // Loops until there are no more tokens.
                        while (st.hasMoreTokens())
    String token = st.nextToken(); // reads next
    next token.
    // Only if the token encounters the String
    tring "membera".
                             if(token.equals("membera"))
                                  // *****THE PROBLEM LIES HERE....I GUESS
    // need to read the next line after encountering the word membera in text file
    nextLine = br.readLine(); // gets next line.
    setA.addMember(nextLine); // adds a member to
    ber to the set.
    // Displays members present in the set if
    set if vector is not empty.
                                  if (! setA.isSetEmpty())
                                       setA.printMember(); // print members present.
    // Displays the number of member/s present in
    ent in the vector.
    System.out.println("Number of set members: " +
    s: " + setA.countMember());
              // Catches and displays exceptions.
              catch (FileNotFoundException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              catch (IOException exp)
                   System.out.println(exp.getMessage());
                   exp.printStackTrace();
              finally
                   try
                        // if file is found
                        if (fr != null)
                             // close file
                             fr.close();
                   catch (IOException exp)
                        exp.printStackTrace();
         } // end public static void main(String args[]).
    } // end public class SetTestLauncher.

  • How to read the whole text file lines using FTP adapter

    Hi all,
    How to read the whole text file lines when error occured middle of the text file reading.
    after it is not reading the remaining lines . how to read the whole text file using FTP adapter
    pls can you help me

    Yes there is you need to use the uniqueMessageSeparator property. Have a look at the following link for its implementation.
    http://download-west.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/adptr_file.htm#CIACDAAC
    cheers
    James

  • How to read in a text file of race lap times....

    How do i read in a text file containing lap times from a race for one driver?
    I have the times down 1 column and look like this.
    I then want to add the times up to get a total race time. I have been looking at the Calendar class and the simpleDateFunction but not sure how to go about it.
    1'43.857
    1'37.860
    1'38.147
    1'37.922
    1'37.662
    1'37.639
    1'37.621
    1'37.728
    1'37.508
    1'37.990
    1'38.114
    1'38.177
    1'38.162
    1'37.847
    1'38.013
    1'38.196
    1'37.963
    1'37.924
    1'38.038
    1'37.962
    Thanks
    Trev

    Considering that your times have non-numerical chars you have no choice but to read them as Strings. Once you have done that you will need to parse the times yourself, ie spilt it into the three separate bits of data. Then you can use the Calendar class if you wish or you can keep a running tally yourself. Just don't forget to tick over seconds when milliseconds reaches 999 and tick over minutes when seconds reach 59.

  • Reading from a text file in to an array, help please

    I have the following
    public class date extends Loans{
    public int dd;
    public int mm;
    public int yyyy;
    public String toString() {
    return String.format( "%d,%d,%d", mm, dd, yyyy );
    public class Loans extends Borrowing {
    public String name;
    public String book;
    public date issue;
    public char type;
    public String toString(){
    return String.format( "%s, %s, %s, %s", name, book, issue, type );
    import java.util.Scanner;
    import java.io.*;
    public class Borrowing extends BorrowingList {
    private Loans[] Loaned = new Loans[20];
    if i want to read in from a text file in to that array how do i do it?

    sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
    C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
    symbol : class IOException
    location: class Menu
    }catch(IOException e){
    Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    1 error
    BUILD FAILED (total time: 0 seconds)
    for this line
    }catch(IOException e){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to read from MS  Excel file ?

    Which is the best way to read from a MS Excel file ?
    I need to read both "column-wise" and "row-wise".
    Is there any free software or java api which does this. I have come across some paid softwares which do that, but i would prefer using something which is free.
    I have tried using the "save as" option to save as tab delimited, comma delimited, unicode text ... but they raise too many exceptions, and cannot be read as we read a normal text file.
    Please do suggest.
    Thanks.

    http://forum.java.sun.com/thread.jsp?forum=31&thread=289935
    http://forum.java.sun.com/thread.jsp?forum=4&thread=285062
    If you would search of the forums, you would find these two threads, and probably many others. They not only include pointers to what you ask but discussions of the pros and cons among various solutions.
    /Mel

  • Reading from a text file and displaying the contents with in a frame

    Hi All,
    I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
    pcode1,pname1,price1,sname1,
    pcode2,pname2,price2,sname1,
    I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
    Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
    void ReadTextFile()
                        FileInputStream fis=new FileInputStream(new File("nieman.txt"));
                         InputStreamReader isr=new InputStreamReader(fis);
                         char[] buf=new char[1024];
                         isr.read(buf,0,1024);
                         fstr=new String(buf);
                         String Tokenizer st=new StringTokenizer(fstr,",");
                         while(st.hasMoreTokens())
                                          pcode1=st.nextToken();
                               pname1=st.nextToken();
              price1=st.nextToken();
                              sname1=st.nextToken();
         } //close of while loop
                    } //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
    Thanks in advance.

    If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
    MyClassName.pcode1;
    MyClassName.pname1;
    MyClassName.price1;
    MyClassName.sname1

  • How to remove noisy data points read from a text file

    Reading data measurements taken in from a txt file.  How do I get rid of noise aside from going into the text file and deciding point by point what to delete.

    Well going in point by point and deleting is certainly one way of going about it. Of course that would defeat the entire purpose of having this great programming enviroment that is capable of doing that kind of thing for us.
    Is your text file small enough to upload? Obviously you know what the criteria are for judging whether or not a data point is acceptable so it should be simple enough to program. Give us a bit more information and I can assure you there will be a race between LabVIEW experts to see who can post the cleanest, simplest, and fastest piece of code that will do what you need. My wager is on altenbach, but there are a few others here that are almost as impressive.

  • How do I read from a text file that is longer than 65536 lines and write the data to an Excel spreadshee​t and have the data write to a new column once the 65536 cells are filled in a column?

    I have data that is in basic generic text file format that needs to be converted into Excel spreadsheet format.  The data is much longer than 65536 lines, and in my code I haven't been able to figure out how to carry over the data into the next column.  Currently the conversion is done manually and generates an Excel file that has a total of 30-40 full columns of data.  Any suggestions would be greatly appreciated.
    Thanks,
    Darrick 
    Solved!
    Go to Solution.

    No need to use nested For loops. No need for any loop anyway. You just have to use a reshape array function. The picture below shows how to proceed.
    However, there may be an issue if your element number is not a multiple of the number of columns : zero value elements will be added at the end of the last column in the generated 2D array. Now the issue depends on the way you intend store the data in the Excel spreadsheet : you could convert the data as strings, replace the last zero values with empty strings, and write the whole 2D array to a file (with the .xls extension ) using the write to spreadsheet function. Only one (minimal) problem : define the number of decimal digits to be used;
    or you could write the numeric array directly to a true Excel spreadsheet, using either the NI report generation tools or ActiveX commands, then replace the last elements with empty strings.
    We need more input from you to decide how to solve these last questions. 
    Message Edité par chilly charly le 01-13-2009 09:29 PM
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    Example_VI.png ‏10 KB

  • Read from a text file line by line

    Hi,
    I am new to Labview and I am trying to output a text file line by line. For example if my text file is
    START
    SETRPM 1000
    WAIT 10s
    RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
    WAIT 5s
    RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
    END
    I want it to output
    START
    SETRPM 1000
    SETMAF 5 ...and so on
    I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
    Thank you!
     

    Your program does exactly what you asked it to do.  In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register.  This data will consist of the first line of the (assumed-)multi-line file you specified.
    I suppose your question is "Why is it only showing me one line?"  This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
    Bob Schor
    P.S. -- I pointed your code at a text file of 7 lines on my PC.  When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text.

  • How to read a Unicode text file in a non-unicode SAP system

    I'm currently has a text file which is saved as UTF-8 format. And inside this file has Thai characters.
    However, my SAP system is a non-unicode system.
    When I use the code
    open dataset DSN for output in TEXT MODE encoding UTF-8
    the thai characters become some funny characters.
    How can I solve this in the ABAP program without changing the system from non-unicode to unicode system?

    Hi Eswar,
       How can I check whether the code page for THAI already installed or not in SAP system?
       Here is the code I use to test to read a file that saved as UTF-8.
    DATA: l_filepath         TYPE string.
    DATA : BEGIN OF l_filepath_str OCCURS 0,
                 comm(1000)  TYPE c,
               END OF l_filepath_str.
    DATA: l_datasetsucc LIKE rlgrap-filename.
    l_filepath = '/BAAC/Files/APP_.txt'.
    OPEN DATASET l_filepath FOR INPUT IN TEXT MODE ENCODING UTF-8.
    IF sy-subrc EQ 0.
      DO.
        CLEAR l_filepath_str.
        READ DATASET l_filepath INTO l_filepath_str.
        IF sy-subrc EQ 0.
          APPEND l_filepath_str.
        ELSE.
          EXIT.
        ENDIF.
      ENDDO.
    ELSE.
      WRITE:/ 'Error reading from file:', sy-subrc.
    ENDIF.
    CLOSE DATASET l_filepath.
    LOOP AT l_filepath_str.
      WRITE: / l_filepath_str-comm.
    ENDLOOP.
        It returns me a runtime error. Any idea?

Maybe you are looking for

  • Loading multiple swfs using air 3.6 for ios

    Adobe, can you please provide us with the code to load multiple swf files for ios. Please provide examples. The code below loads multiple swfs, but the swfs stall, so this does not seem to be a solution. Code description: A flash file made up of 4 fr

  • Can I get books from any other source than iBooks and read them in iBooks?

    I find that the iBooks Store list of titles is somewhat limited and some popular titles are not available. Can I purchase an ebook from another source, download it and then read it in iBooks? I have the iPad 2' my daughter has a Kindle but when it co

  • Setting Minimum RSSI threshold for client connections

    Hi, We are deploying a new wireless network for guest users of private lounges at airports, using a 5508 WLC and 3501 AP's. The SSID uses open L2 authentication with a web auth passthrough login splash page. We require preventing people outside these

  • Design document

    hi group, can any body provide some links,to design and analysis document of e-commerce,retailing e.t.c, thanks, kamath.

  • Call methods from view controller to another (enhanced) view controller!

    Dear All, Is it possible to use/call methods from view controller to another (enhanced) view controller? Iu2019ve created a view using enhancement in standard WD component. I would like to call one method from standard view controller in the enhanced