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

Similar Messages

  • Reading a Blob (CSV file) and displaying the contents

    Hello Experts,
    I’m currently working on a system that allows the users to upload an Excel spreadsheet (.xls) in the system. The upload page is a PL/SQL cartridge. Then I’ve written a Java servlet (using Oracle Clean Content) to convert the XLS into a CSV and store it back in the database. (it is stored in the “uploaded_files” table as a blob). I’m trying to create another procedure to read the contents of the blob and display a preview of the data on the screen (using an html table (will be done using cartridge)). After the preview, the user can choose to submit the data into the database into the “detail_records” table or simply discard everything.
    Can anyone provide me any guidelines and/or code samples for reading the contents of a blob and displaying it as an html table? My data contains about 10 rows and 20 columns in the spreadsheet. I’ve been looking into using associative arrays or nested tables but I’m getting confused about how to implement them in my situation.
    Any help is greatly appreciated.

    BluShadow,
    Thanks for your response. The reason that it is a blob is that we use the same table for uploaded files for several applications. Some files are text, some excel, some other formats. Hence the table has been set up in a generic sense.
    However, in my procedure, I'm using
    DBMS_LOB.createtemporary and
    DBMS_LOB.converttoclob
    Is there any way you could possibly provide an example of how to read the contents of the file?

  • I need to read data from a text file and display it in a datagrid.how can this be done..please help

    hey ppl
    i have a datagrid in my form.i need to read input(fields..sort of a database) from a text file and display its contents in the datagrid.
    how can this  be done.. and also after every few seconds reading event should be re executed.. and that the contents of the datagrid will keep changing as per the changes in the file...
    please help as this is urgent and important.. if possible please provide me with an example code as i am completely new to flex... 
    thanks.....  

    It's not possible to read from a file without using classes from the core API*. You'll have to get clarification from your instructor as to which classes are and are not allowed.
    [http://java.sun.com/docs/books/tutorial/essential/io/]
    *Unless you write a bunch of JNI code to replicate what the java.io classes are doing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Hi i am new to labview. i want to extract data from a text file and display it on the front panel. how do i proceed??

    Hi i am new to labview
    I want to extract data from a text file and display it on the front panel.
    How do i proceed??
    I have attached a file for your brief idea...
    Attachments:
    extract.jpg ‏3797 KB

    RoopeshV wrote:
    Hi,
    The below code shows how to read from txt file and display in the perticular fields.
    Why have you used waveform?
    Regards,
    Roopesh
    There are so many things wrong with this VI, I'm not even sure where to start.
    Hard-coding paths that point to your user folder on the block diagram. What if somebody else tries to run it? They'll get an error. What if somebody tries to run this on Windows 7? They'll get an error. What if somebody tries to run this on a Mac or Linux? They'll get an error.
    Not using Read From Spreadsheet File.
    Use of local variables to populate an array.
    Cannot insert values into an empty array.
    What if there's a line missing from the text file? Now your data will not line up. Your case structure does handle this.
    Also, how does this answer the poster's question?

  • Having trouble reading specific lines from a text file and displaying them in a listbox

    I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
    occurred in mscorlib.dll"
    Below is the code from that form. 
    Option Strict On
    Option Infer Off
    Option Explicit On
    Public Class frmInventoryReport
    Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
    Dim intTemp As Integer
    intTemp = lineNumber
    Return lines(lineNumber - 1)
    lineNumber = intTemp
    End Function
    Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
    For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
    If fileName.ToLower().Contains(phrase.ToLower()) Then
    Return True
    End If
    Next
    Return False
    End Function
    Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim intcase As Integer = 1
    Dim strTemp, strlist, strFile As String
    Dim blnCheck As Boolean = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Do While blnCheck = True
    strFile = "Report Q" & intcase.ToString & ".txt"
    Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
    Dim allLines As List(Of String) = New List(Of String)
    Do While objReader.Peek <> -1
    allLines.Add(objReader.ReadLine())
    Loop
    objReader.Close()
    strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
    lstInventory.Items.Add(strlist)
    intcase += 1
    strTemp = intcase.ToString
    strFile = "Report Q" & intcase.ToString & ".txt"
    blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
    Loop
    End Sub
    End Class
    Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!

    Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
    Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it.  Is there anything other than name and cage number that should be associated with each animal?
    You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple.  Here's a simple class example:
    Public Class Animal
    Public Property Name As String
    Public Property Cage As String
    Public Overrides Function ToString() As String
    Return String.Format("{0} - {1}", Name, Cage)
    End Function
    End Class
    With that you can use a routine like the following to loop through all of the files and read each one:
    Dim animals As New List(Of Animal)
    Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
    For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
    Using reader As New System.IO.StreamReader(filePath)
    Dim lineIndex As Integer = 0
    Dim currentAnimal As New Animal
    While Not reader.EndOfStream
    Dim line As String = reader.ReadLine
    If lineIndex = 0 Then
    currentAnimal.Name = line
    ElseIf lineIndex = 22 Then
    currentAnimal.Cage = line
    Exit While
    End If
    lineIndex += 1
    End While
    animals.Add(currentAnimal)
    End Using
    Next
    'do something to display the animals list
    Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView.  If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
    There are lots of options depending on what you want and what all you need to do.
    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

  • Reading the XML file and displaying the string with the desired output

    Hi Gurus,
    I have an xml file as below.
    catalog>
    <book>
    <id>101</id>
    <genre>Computer</genre>
    <author>Jim Cortez</author>
    <title>XML for dummies</title>
    <price>44.95</price>
    <description>An in-depth look at creating mashed potatoes
    with XML.</description>
    </book>
    <book>
    <id>102</id>
    <author>George Bush</author>
    <title>I'm the decider</title>
    <genre>Fantasy</genre>
    <price>0.95</price>
    <description>I like milk and cookies.</description>
    </book>
    </catalog>
    I would like to display the Output as
    [<catalog>:1]
    [<book>:1]
    [<id>:1]
    [101:3]
    [</id>:2]
    [<genre>:1]
    [Computer:3]
    [</genre>:2]
    [<author>:1]
    [Jim Cortez:3]
    [</author>:2]
    [<title>:1]
    [XML for dummies:3]
    ............ etc., etc.,,
    here is the code template.......
    import java.io.*;
    class TagScanner implements TokenStream {
    public static final int BEGIN_TAG_TYPE = 1;
    public static final int END_TAG_TYPE = 2;
    public static final int TEXT_TYPE = 3;
    protected Reader reader = null;
    /** Lookahead char */
    protected char c;
    /** Text of currently matched token */
    protected StringBuffer text = new StringBuffer(100);
    public TagScanner(Reader reader) throws IOException {
    this.reader = reader;
    nextChar();
    protected void nextChar() throws IOException {
    c = (char)reader.read();
    public Token nextToken() throws IOException {
    if ( start of a tag ) {
    // scarf until end of tag
    // type is either BEGIN_TAG_TYPE or END_TAG_TYPE
    if ( end of file ) {
    type = Token.EOF_TYPE;
    text = "end-of-file";
    else {
    // scarf until start of a tag
    type = TEXT_TYPE;
    if ( just whitespace ) {
    // ignore and get another token
    return new Token(type, text.toString());
    Can someone please provide me the logic for the code please........... here is the complete link of the excersie
    http://www.antlr.org/wiki/display/CS652/Lexer+for+XML
    Many Thanks
    -M

    Can someone please provide me the logic for the code please..........The logic is pretty well spelled out for you in the description of the assignment and the outline for the code you provided. If you mean
    Can someone please do my homework for me....The answer to that is usually yes, someone can do your homework for you, but no, they usually won't actually do it for you.
    However, if you are really stuck on what to do, you should consider:
            if ( start of a tag ) {How would you know that you are at the start of a tag? Once you can answer that, the rest sort of works itself out as long as
                // scarf until end of tagyou realize what it means to 'scarf' and how to determine when an end-of-tag is reached (hint, very similar as to how to determine if you are at the start-of-tag).

  • Read from a .db file and use the values within a program

    each account has 3 values.. (password, balance,id_number)
    my .db file contains the following.
    pass201 250 9885 pass202 300 5547 pass203 700 1123
    (this is 3 accounts)
    I need to be able to read from this file and use each attribute within my program... HELP!

    String[][] accounts = null;
    try
         // Open a file input stream
         FileInputStream fileContents = new FileInputStream("filename");
         byte[] data = new byte[fileContents.available()];
         fileContents.read(data);
         fileContents.close();
         String contents = new String(data);
         StringTokenizer values = new StringTokenizer(data); // using space character as delimiter
         // Using 3 values per line
         int lines = (int)(values.countTokens()/3);
         int columns = 3;
         accounts = new String[lines][columns];
         for(int i=0; i<lines; i++)
              for(int j=0; j<columns; j++)
                   accounts[i][j] = values.nextToken();
    catch(Exception error)
         // debug stuff
    }

  • Powershell script for pinging computers from a text file and displaying output with ip address

    i am currently using the following script to display the computers that are pinging, i also want the script to display the
    ipaddress along with the results but the results are displayed not properly, i want the result to be displayed in a table or list format, what am i missing?
    $ServerName = Get-Content "C:\scripts\computers.txt"
    foreach ($Server in $ServerName) {
    if (test-Connection -ComputerName $Server -Count 2 -Quiet) {
    "$Server is Pinging "
    } else
    {"$Server not pinging"
    foreach ($server in $servername) {
    Get-WmiObject -class "Win32_NetworkAdapterConfiguration"|Select-Object IPAddress|Format-List

    Not sure I completely understand your question but looking at the code you posted I see one fairly simple change that may be what you are missing...your Get-WMIObject statement never passes a server name to the command.  You loop through the list
    you obtained but never actually pass that to anything.  So the simple change would be to just do the following...
    foreach($server in $servername)
    Get-WMIObject -class win32_NetworkAdapterConfiguration -computername $server
    | select IPAddress | FT -auto
    you could also tuck that command into the previous foreach/if/else statement and just do each one that actually responds. 

  • Problem in reading this particular text file, what is the problem with it..

    Hai to all..,
    I had developed an application to read the text file that is stored in my computer from mobile, all are working fine but some files create problems in reading the file content, like the file i had attached with this..
    Can any one please tell why this particular file creates problem in reading the contents...
    I had attached a text file with this...
    and the code I am using is
    int getcharcount;
    FileInputStream fstream = new FileInputStream(filename);
    InputStreamReader in = new InputStreamReader(fstream);
    while ((getcharcount = in.read()) != 0)
         getchar = getchar + (char) getcharcount;
    System.out.println("Full File Content :"+getchar);
    I try'd with BufferedReader also, but have the same problem,
    Can any one please give me a solution for this..

    Hai to all..,
    Sorry for the previous posting,
    I had developed an application to read the text file that is stored in my computer from mobile, all are working fine but some files create problems in reading the file content, like the file i had attached with this..
    Can any one please tell why this particular file creates problem in reading the contents...
    and the code I am using is
    int getcharcount;
    FileInputStream fstream = new FileInputStream(filename);
    InputStreamReader in = new InputStreamReader(fstream);
    while ((getcharcount = in.read()) != 0)
         getchar = getchar + (char) getcharcount;
    System.out.println("Full File Content :"+getchar);
    I try'd with BufferedReader also, but have the same problem,
    Can any one please give me a solution for this..The error I am getting is
    Full File Content :ÿþC
    But the file contains plain text only..
    Edited by: Kamal Raj on Oct 17, 2010 10:22 PM

  • 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.

  • Help needed regarding reading in a text file and tokenizing strings.

    Hello, I require help with a task I've been set, which asks me to read in a text file, and check the contents for errors. The text file contains lines as follows.
    surname:forename:1234:01-02-06
    I can read in the file, but dont know how to split the strings so each token can be tested (ie numbers in the name tokens)
    However, I am not allowed to use regex functions, only those found in java.io.*
    I think i should be putting the tokens into an array, but have had no luck so far in doing so. Any help would be appreciated.

    public class Validator {
         public static void main(String args[]) {
              String string = "Suname:Forename:1234:01_02-06";
              String stringArray[] = string.split(":");
              System.out.println (validateLetters(stringArray[0]));//returns true
              System.out.println (validateNumbers(stringArray[3]));//returns false
         static boolean validateLetters(String s) {
                 for(int i = 0; i < s.length(); i++) {
                 char c = s.charAt(i);
                 if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z')) {
                         return false; //return false if one of characters is other than a-z A-Z
                 }//end if
                 }//end for
                 return true;
         }//end validateLetters
         static boolean validateNumbers(String s) {
                 for(int i = 0; i < s.length(); i++) {
                 char c = s.charAt(i);
                 if ((c < '0' || c > '9') && (c != '-')) {
                         return false; //return false if one of characters is other than 0-9 or -
                 }//end if
                 }//end for
                 return true;
         }//end validateNumbers
    }

  • 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.

  • 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

  • How can i read the text files and buffer the data in Vector?

    hi. I have been running into this problem for days, but with no luck and losing right direction.
    The problem is : I am trying to read a text file and buffer the data into a
    Queue for each user.
    the sample text file is as below:( 1st column is timestamp, 2nd is user_id, 3rd is packet_id, 4th is packet_seqno, 5th is packet_size)
    0 1 1 1 512
    1 2 1 2 512
    2 3 1 3 512
    3 4 1 4 512
    4 5 1 5 512
    5 6 1 6 512
    6 7 1 7 512
    7 8 1 8 512
    8 9 1 9 512
    9 10 1 10 512
    10 1 2 11 512
    11 2 2 12 512
    12 3 2 13 512
    13 4 2 14 512
    14 5 2 15 512
    15 6 2 16 512
    16 7 2 17 512
    17 8 2 18 512
    18 9 2 19 512
    19 10 2 20 512
    20 1 3 21 512
    21 2 3 22 512
    22 3 3 23 512
    23 4 3 24 512
    24 5 3 25 512
    25 6 3 26 512
    26 7 3 27 512
    27 8 3 28 512
    28 9 3 29 512
    29 10 3 30 512
    30 1 4 31 512
    31 2 4 32 512
    32 3 4 33 512
    33 4 4 34 512
    34 5 4 35 512
    35 6 4 36 512
    36 7 4 37 512
    37 8 4 38 512
    38 9 4 39 512
    39 10 4 40 512
    40 1 5 41 512
    41 2 5 42 512
    42 3 5 43 512
    43 4 5 44 512
    44 5 5 45 512
    45 6 5 46 512
    46 7 5 47 512
    47 8 5 48 512
    48 9 5 49 512
    49 10 5 50 512
    50 1 6 51 512
    51 2 6 52 512
    52 3 6 53 512
    53 4 6 54 512
    54 5 6 55 512
    55 6 6 56 512
    56 7 6 57 512
    57 8 6 58 512
    58 9 6 59 512
    59 10 6 60 512
    60 1 7 61 512
    61 2 7 62 512
    62 3 7 63 512
    63 4 7 64 512
    64 5 7 65 512
    65 6 7 66 512
    66 7 7 67 512
    67 8 7 68 512
    68 9 7 69 512
    69 10 7 70 512
    70 1 8 71 512
    71 2 8 72 512
    What I wanna do is to read all the data above and buffer them in a queue for each user( there are only 10 users in total).
    I already created a class called Class packet:
    public class packet {
        private int timestamp;
        private int user_id;
        private int packet_id;
        private int packet_seqno;
        private int packet_size;
        /** Creates a new instance of packet */
        public packet(int timestamp,int user_id, int packet_id,int packet_seqno, int packet_size)
            this.timestamp = timestamp;
            this.user_id=user_id;
            this.packet_id=packet_id;
            this.packet_seqno=packet_seqno;
            this.packet_size=packet_size;
    }then I wanna to create another Class called Class user which I can create a queue for each user (10 users in total) to store type packet information. the queue for each user will be in the order by timestamp.
    any idea and sample code will be appreciated.

    Doesn't sound too hard to me. Your class User (the convention says to capitalize class names) will have an ArrayList or Vector in it to represent the queue, and a method to store a Packet object into the List. An array or ArrayList or Vector will hold the 10 user objects. You will find the right user object from packet.user_id and call the method.
    Please try to write some code yourself. You won't learn anything from having someone else write it for you. Look at sample code using ArrayList and Vector, there's plenty out there. Post in the forum again if your code turns out not to behave.

  • // Code Help need .. in Reading CSV file and display the Output.

    Hi All,
    I am a new Bee in code and started learning code, I have stared with Console application and need your advice and suggestion.
    I want to write a code which read the input from the CSV file and display the output in console application combination of first name and lastname append with the name of the collage in village
    The example of CSV file is 
    Firstname,LastName
    Happy,Coding
    Learn,C#
    I want to display the output as
    HappyCodingXYZCollage
    LearnC#XYXCollage
    The below is the code I have tried so far.
     // .Reading a CSV
                var reader = new StreamReader(File.OpenRead(@"D:\Users\RajaVill\Desktop\C#\input.csv"));
                List<string> listA = new List<string>();
                            while (!reader.EndOfStream)
                    var line = reader.ReadLine();
                    string[] values = line.Split(',');
                    listA.Add(values[0]);
                    listA.Add(values[1]);
                    listA.Add(values[2]);          
                    // listB.Add(values[1]);
                foreach (string str in listA)
                    //StreamWriter writer = new StreamWriter(File.OpenWrite(@"D:\\suman.txt"));
                    Console.WriteLine("the value is {0}", str);
                    Console.ReadLine();
    Kindly advice and let me know, How to read the column header of the CSV file. so I can apply my logic the display combination of firstname,lastname and name of the collage
    Best Regards,
    Raja Village Sync
    Beginer Coder

    Very simple example:
    var column1 = new List<string>();
    var column2 = new List<string>();
    using (var rd = new StreamReader("filename.csv"))
    while (!rd.EndOfStream)
    var splits = rd.ReadLine().Split(';');
    column1.Add(splits[0]);
    column2.Add(splits[1]);
    // print column1
    Console.WriteLine("Column 1:");
    foreach (var element in column1)
    Console.WriteLine(element);
    // print column2
    Console.WriteLine("Column 2:");
    foreach (var element in column2)
    Console.WriteLine(element);
    Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]

Maybe you are looking for

  • Load relationships from only one BP,  from R/3 to CRM

    Hello, I have downloaded one BP from R/3 to CRM, but relationships (Employee responsible, Sales representative, Ship-to party, etc...) are not downloaded into this BP. The individual employees, ship-to party, etc... already exist in CRM, but not appe

  • Preferences.removeNode() doesn't actually remove the preference node

    I have the following method in a class I use to modify system preferences:     public boolean removePreferenceNode (String nodePath)         throws BackingStoreException {         // get the preferences node specified by the node path         Prefere

  • Import Word to RH8 - can't select Style sheet to apply

    When importing a Word file to RH8 the new dialogue box series needs me to apply my style sheet on the 2nd screen...but even though Help says that a list will be provided, it is greyed out and I can't chose/add one: This causes all the numbers and bul

  • How to i add an image path with spry data set

    hi how to i add an image path with spry data set. I made a xml file and then created a data set in html but image won't load this is my XML <?xml version="1.0" encoding="UTF-8"?> <banner width = "185" height = "400">     <item>         <image scr = "

  • Distribution agent could not apply a generated snapshot file

    In my case , some main info as follows . after add a article into one publication , then manually execute sp_startpublication_snapshot to generate snapshot ,and with no errors , but distribution agent didnot apply it . How to fix ? Type:Transaction R