Reading through a text file and then sorting

I'm having a lot of problems with this.
I have to read through a text file and I have to split the string up so that it is seperated into individual tokens. A line from the text file looks like this. addEvent(new Bell(tm + 9000)). I have to grab the addEvent, new, Bell, tm and 9000 and store it in a linkedlist. After reading through the whole text file I have to sort the the linked list based on the number. ie: 9000. Is there any way to do this? I currently break up the text file using a StringTokenizer object but then i am uncertain on how to add it to a linked list and then sort each line based on the number. Any help would be appreciated.
Joe

Sorry to bother you Ben but I just can't get my head wrapped around this. Here is exactly what I have to do:
After reading, Events must be stored in the EventSet according to the time they are to occur. Assume that no time number is more than 8 digits long. Restart() must be able to deal appropriately with any order of the Events. To accomplish this have Restart() save the relevant Event information in an LinkedList of strings and sort the Events by time before adding each event to EventSet. Use the <list>.add() to set up your linked list. This is shown in c09:List1.java and Collections.sort(<list>) shown in c09:ListSortSearch. Modify the Bell() to output a single "Bing!". When you read in a Bell event generate the appropriate number of Bell events as indicated by rings. These must be set to the correct times. This is an alternative to generating the new Bell events within Bell(). It will allow them be sorted into their correct time sequence. At this point the output of the program should be identical the original program.
After the intitial start, when restarting Restart() must provide to the user the option to recreate the EventSet from the linked list or read in a new file (supplied by the user). This must be achieved by prompting the user at the console. Please also allow the user the option to quit the program at this stage.
Main Program Code:
public class GreenhouseControls extends Controller
private boolean light = false;
private boolean water = false;
private String thermostat = "Day";
private boolean fans = false;
     private class FansOn extends Event
          public FansOn(long eventTime)
               super(eventTime);
          public void action()
          // Put hardware control code here to
          // physically turn on the Fans.
          fans = true;
          public String description()
               return "Fan is On";
     private class FansOff extends Event
          public FansOff(long eventTime)
               super(eventTime);
          public void action()
          // Put hardware control code here to
          // physically turn off the Fans.
          fans = false;
          public String description()
               return "Fans are Off";
     private class LightOn extends Event
          public LightOn(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here to
               // physically turn on the light.
               light = true;
          public String description()
               return "Light is on";
     private class LightOff extends Event
          public LightOff(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here to
               // physically turn off the light.
               light = false;
          public String description()
               return "Light is off";
     private class WaterOn extends Event
          public WaterOn(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here
               water = true;
          public String description()
               return "Greenhouse water is on";
     private class WaterOff extends Event
          public WaterOff(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here
               water = false;
          public String description()
               return "Greenhouse water is off";
     private class ThermostatNight extends Event
          public ThermostatNight(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here
               thermostat = "Night";
          public String description()
               return "Thermostat on night setting";
     private class ThermostatDay extends Event
          public ThermostatDay(long eventTime)
               super(eventTime);
          public void action()
               // Put hardware control code here
               thermostat = "Day";
          public String description()
               return "Thermostat on day setting";
     // An example of an action() that inserts a
     // new one of itself into the event list:
     private int rings;
     private class Bell extends Event
          public Bell(long eventTime)
               super(eventTime);
          public void action()
               // Ring every 2 seconds, 'rings' times:
               System.out.println("Bing!");
               if(--rings > 0)
          addEvent(new Bell(System.currentTimeMillis() + 2000));
          public String description()
               return "Ring bell";
     private class Restart extends Event
          public Restart(long eventTime)
               super(eventTime);
          public void action()      
               long tm = System.currentTimeMillis();
               // Instead of hard-wiring, you could parse
               // configuration information from a text
               // file here:
          try
          BufferedReader in = new BufferedReader(new FileReader("Event Config.txt"));
          String str;
               String[] l1 = new String[5];
               LinkedList l2 = new LinkedList();
          while((str = in.readLine()) != null )
                    StringTokenizer st = new StringTokenizer(str, "(+); ");
                    int nIndex = 0;
                    while (st.hasMoreTokens())
                         l1[nIndex] = st.nextToken();
                    //System.out.println(st.nextToken());
                         nIndex++;
                    l2.add(l1);
               String[] s1 = (String[])l2.get(1);
               for(int i = 0; i < s1.length; i++)
                    System.out.println(s1);
               Comparator comp = s1[4];
               Collections.sort(l2, comp);
          in.close();
          catch (IOException e)
rings = 5;
addEvent(new ThermostatNight(tm));
addEvent(new LightOn(tm + 1000));
addEvent(new LightOff(tm + 2000));
addEvent(new WaterOn(tm + 3000));
addEvent(new WaterOff(tm + 8000));
addEvent(new Bell(tm + 9000));
addEvent(new ThermostatDay(tm + 10000));
// Can even add a Restart object!
addEvent(new Restart(tm + 20000));*/
public String description() {
return "Restarting system";
public static void main(String[] args) {
GreenhouseControls gc =
new GreenhouseControls();
long tm = System.currentTimeMillis();
gc.addEvent(gc.new Restart(tm));
gc.run();
} ///:~
Examples File:
addEvent(new ThermostatNight(tm));
addEvent(new Bell(tm + 9000));
addEvent(new Restart(tm + 20000));
addEvent(new LightOn(tm + 1000));
addEvent(new WaterOn(tm + 3000));
rings = 5;
addEvent(new FansOn(tm + 4000));
addEvent(new LightOff(tm + 2000));
addEvent(new FansOff(tm + 6000));
addEvent(new WaterOff(tm + 8000));
addEvent(new WindowMalfunction(tm + 15000));
addEvent(new ThermostatDay(tm + 10000));
EventSet.java Code:
// This is just a way to hold Event objects.
class EventSet {
private Event[] events = new Event[100];
private int index = 0;
private int next = 0;
public void add(Event e) {
if(index >= events.length)
return; // (In real life, throw exception)
events[index++] = e;
public Event getNext() {
boolean looped = false;
int start = next;
do {
next = (next + 1) % events.length;
// See if it has looped to the beginning:
if(start == next) looped = true;
// If it loops past start, the list
// is empty:
if((next == (start + 1) % events.length)
&& looped)
return null;
} while(events[next] == null);
return events[next];
public void removeCurrent() {
events[next] = null;
public class Controller {
private EventSet es = new EventSet();
public void addEvent(Event c) { es.add(c); }
public void run() {
Event e;
while((e = es.getNext()) != null) {
if(e.ready()) {
e.action();
System.out.println(e.description());
es.removeCurrent();
} ///:~
Event.java Code
abstract public class Event {
private long evtTime;
public Event(long eventTime) {
evtTime = eventTime;
public boolean ready() {
return System.currentTimeMillis() >= evtTime;
abstract public void action();
abstract public String description();
} ///:~
Is this problem easier than I think it is? I just don't know what to add to the linkedList. A LinkedList within a linkedList? I find this problem pretty difficult. Any help is muchly appreciated.
Joe

Similar Messages

  • Powershell script - how to read a registry hive and store the value in text file and then again read the text file to write the values back in registry

    Hi All,
    powershell script Method required to read a value from registry and then taking the backup of that values in some text file.
    For example the hive is
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\Path
    and under path i need to take back up  of values in some text file and then put some value in the registry after back is taken in text file.
    Also how to read the text file values so that we can again write to registry hive  back from the back up text file.
    Your help is much appreciated.
    Umeed4u

    I think you need to read this first:
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/a0def745-4831-4de0-a040-63b63e7be7ae/posting-guidelines?forum=ITCG
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

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

  • Automator - Loop through a text file and process data through a 3rd party software

    Just stumbled on Automator the other day (I am a mac n00b) and would like to automate the processing of a text file, line-by-line, using a third party tool.  I would like Automator to loop through the text file one line at a time, copy the string and keep as a variable.  Next, place the variable data (copied string) into the text field of the 3rd party software for processing.  Once the processing is complete, I would like Automator to fetch the next line/string for processing.  I see items like "copy from clipboard" and  "variables" within the menu but I am not finding much documentation on how to utilizle this tool.  Just hear how potentially powerful it is. 
    The 3rd party software is not a brand name, just something made for me to process text.  I may have to use mouse clicks or tabs + [return] to navigate with Automator.  A term I heard on Bn Walldie's itunes video series was "scriptable software" for which I don't think this 3rd party app would be. 
    Kind regards,
    jw

    Good news and bad news...
    The good news is that it should be entirely possible to automate your workflow.
    The bad news is that it will be a nightmare to implement via Automator, if it's even possible.
    Automator is, essentially a pretty interface on top of AppleScript/Apple Events, and with the pretty interface comes a certain stranglehold on features. Knowing how to boil rice might make you a cook, but understanding flavor profiles and ingredient combinations can make you a chef, and it's the same with AppleScript and Automator. Automator's good at getting you from points A to B but if there are any bumps in the road (e.g. the application you're using isn't scriptable) then it falls apart.
    What I'm getting at is that your requirements are pretty simple to implement in AppleScript because you can get 'under the hood' and do exactly what you want, as opposed to Automator's restricted interface.
    The tricky part is that if no one else can see this app it's going to be hard to tell you what to do.
    I can give you the basics on reading a file and iterating through the lines of text in it, and I can show you how to 'type' text in any given application, but it may be up to you to put the pieces together.
    Here's one way of reading a file and working through each line of text:
    -- ask the user for a file:
    set theFile to (choose file)
    -- read the file contents:
    set theFileContents to (read file theFile)
    -- break out the lines/paragraphs of text:
    set theLines to paragraphs of theFileContents
    -- now iterate through those lines, one by one:
    repeat with eachLine in theLines
      -- code to perform for eachLine goes here
    end repeat
    Once you have a line of text (eachLine in the above example) you can 'type' that into another application via something like:
    tell application "AppName" to activate
    tell application "System Events"
              tell process "AppName"
      keystroke eachLine
              end tell
    end tell
    Here the AppleScript is activating the application and using System Events to emulate typing the contents of the eachLine variable into the process. Put this inside your repeat loop and you're almost there.

  • Help with reading in a text file and arrays

    I need to read in a text file with info like this for example
    dave
    martha
    dave
    billy
    I can read the information into an array and display the names but what I need to do is display how many times the same name is in the file for example the output should be
    dave 2
    martha 1
    billy 1
    How can I accomplish this? Would I use a Compareto Method to find
    duplicate names?

    Hi,
    I would recommend storing them in a Hashtable.. something like this:
    Hashtable names = new Hashtable() ;
    String s ;
    while( ( s = bufferedReader.readLine() ) != null ) {
        if ( names.contains( s ) ) {
           names.put( s , new Integer( names.get(s)+1 ) ) ;
        else {
           names.put( s , new Integer( 1 ) ) ;
    }Then the hashtable will contain a set of keys and values, which are the names and counts respectively.
    Kenny

  • 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

  • Read in a text file and parse at spaces

    I need to read in a text file, then split it at the spaces (after each word)
    then I would like to save each sentence (maybe as a String Buffer)
    (chek each word to see if a .?! is at the end to determine the end of a sentence)
    Then I need to add the word END to the end of the StringBuffer
    then store each sentence as an element in an arrayList.
    Please Help.

    Cant you just store the entire text file into a really big String, then split it at each "."?
    String text = "";
    //read file into text
    String[] sentences = text.split(".");

  • How do i read a text file and then display the content as a string

    I also would like to strip the string from a certain substring and convert the remaining string into an array of floating point numbers. I was thinking of using the read from spreadsheet vi but I'm not exactly sure if that is going to work. Any help would be greatly appreciated.
    Solved!
    Go to Solution.

    Here is what I have so far. What I am trying to do is to display the text file as a string and then strip the "curve" from the text file. I think I did this successfully. Now I want to convert the remaining string into an array of floating point numbers, and display the numbers into an array and on a waveform graph.
    Attachments:
    hw3datafile.txt ‏1 KB
    Q4.vi ‏7 KB

  • Read data from text file and displaying on Webdynpro

    Hi all,
    I need some help. I have a text file with set of  name, phonenumbers . I want to know how to display the data using Webdynpro. Could some one help me. help is appreciated and I promise to award points for right answer.
    Thank you
    Maruti

    Hi Maruti,
    just open the file and loop on the rows, here an example::
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    FileReader f =  new FileReader("c:
    FileName.ext");
    while ((s = in.readLine()) != null)
    //Here you can put the line into a WD context structure, i.e:
    wdContext.currentContoEconomicoFormElement().setField(s);
    }catch (Exception e) {.....}
    in.close();
    f.close();
    For any others questions, please, let me know.
    Vito

  • 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 in a text file

    For my next project I'm supposed to read in a text file and then compute the legibility index. How do I go about reading in a text file?

    You should check your double equal signs in that procedure....
    Also, the logic you posted above (which I followed), doesn't work perfectly for calculating the number of syllables...for instance, the word "Romeo" contains 3 syllables, but the program will only count two...basically some words which contain the vowels 'io' and 'eo' sometimes are 1 syllable and sometimes are 2....but my program does come close to the indexes listed on the website you mentioned.
    Anyways, here is what I have for a very hackish approach (not modularized, but I don't have time to fix it I'm, I'm off work soon).
    import java.io.*;
    import java.util.*;
    public class LegibilityProfiler
       public static void main(String[] args)
          new LegibilityProfiler();
       public LegibilityProfiler()
          String line,thisWord;
          String[] words;
          int numSentences = 0;
          int numWords = 0;
          int numSyllables = 0;
          int syl,consecutiveVowels,i,j = 0;
          boolean isWord=false;
          char lastvowel=' ';
          try
             BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
             //read through lines until end of file is reached
             while ((line = reader.readLine()) != null)
                //split the words up by spaces
                words = line.split("\\s+");
                //add number of words in the line just read to total count
                numWords+=words.length;
                //process each word in this line
                for(i=0;i<words.length;i++)
                   //initialize variables used for each word
                   syl=0;               //number of syllables in this word
                   isWord=false;        //if "word" contains letters
                   thisWord="";         //stores only the letters in current word
                   consecutiveVowels=0; //number of consecutive vowels
                   lastvowel=' ';       //last vowel processed
                   //process the word
                   for(j=0;j<words.length();j++)
    //if word contains character that completes a sentencce
    if(words[i].charAt(j) == '.' ||
    words[i].charAt(j) == ':' ||
    words[i].charAt(j) == ';' ||
    words[i].charAt(j) == '?' ||
    words[i].charAt(j) == '!')
    numSentences++;
    //for each character in the word, extract only the letters
    if(Character.isLetter(words[i].charAt(j)))
    isWord=true;
    thisWord+=words[i].charAt(j);
    //process only the letters from current word to count vowels
    for(j=0;j<thisWord.length();j++)
    if(isVowel(Character.toLowerCase(thisWord.charAt(j))))
    //if it's the first vowel in a sequence, increase syllable
    if(consecutiveVowels==0)
    syl++;
    //either way, increase consecutive vowel count
    consecutiveVowels++;
    //store last vowel read in
    lastvowel=thisWord.charAt(j);
    else //not a vowel, so make sure count is 0
    consecutiveVowels=0;
    /* once word is processed check to make sure the word didn't
    end with an e, and have no other vowels right before it
    if(consecutiveVowels==1 && (lastvowel=='e' || lastvowel=='E'))
    syl--;
    //if it was a word, increase syllable count
    if(isWord)
    if(syl==0)
    syl=1;
    numSyllables+=syl;
    System.out.println("Number of Words: "+numWords);
    System.out.println("Number Sentences: "+numSentences);
    System.out.println("Number of Syllables: "+numSyllables);
    double ri=206.835-(84.6*numSyllables/numWords)-(1.015*numWords/numSentences);
    System.out.println("\nReadability Index: "+((int)ri));
    reader.close();
    catch(IOException e)
    e.printStackTrace();
    public boolean isVowel(char c)
    return (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='y');

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

  • Read text file and insert into MySQL

    Dears,
    I need to read text file and then insert the data in the correct column in the MySQL database
    example
    I have the following text file:
    field1=1234 field2=56789 field3=444555
    field1=1333 field2=2222 field3=333555
    and so on and so forth ,,note that all rows are identical and just the filed value is changed(there is a dilemeter between fields)
    how can I read field1,field2 and field3 from text file and insert them in the correct table and column in the database.....
    any help?????
    thanks for your cooperation
    Best Regars

    Sure.
    Which part don't you understand?
    1. Reading a text file
    2. Parsing the text file contents.
    3. Relational databases and SQL.
    4. How to create a database.
    5. How to connect to a database in Java.
    6. How to insert records into the database in Java.
    7. How to map Java objects to records in a database.
    This is a pretty nice list. Solve complex problems by breaking them into smaller ones.
    %

  • Reading a text file and connecting two server

    Hi,
    I am newbie at java and I have two question ,
    asume you have two server and a client. every server reads its own text file and the client connect both of them and read output data, and counts number of words. you must use socket programming to communicate to servers.
    I need litle code.
    Thanks for your help

    Hi,
    While using ArrayList, use add your elements into it
    as an object subtype if you do not specify ArryList
    certain type.
    But recall that if you use certain
    type(ArrayList<String>,....), you do not add any
    other different type element.What the heck is this all about Merde?

  • Reading in a text file to GUI for later analysis

    Good Morning any and everyone,
    I'm trying to get a piece of code working to read in a text file and it isn't working very well. The code has been seriously crunched together from a multitude of sources so I suspect that the error has occurred from there.
    The errors that are occurring are "Can't Find Symbol" errors. Only 2 of them though which is a lot less than I had earlier. Now I'm just banging my head against the wall.
    Has anyone got any suggestions as to where I'm going wrong? Anything greatly appreciated.
    (PS> Please be gentle, I'm still a newbie)
    Thanks.
    import java.util.*; // required for List and ArrayList
    import java.io.*; // required for handling and IOExceptions
    import javax.swing.*;
    public class textAnalyser extends JFrame // implements ActionListener
        // the attributes
        // declare a TextArea
        private JTextArea viewArea = new JTextArea(10,55);
        // declare the menu components
        private JMenuBar bar = new JMenuBar();
        private JMenu fileMenu = new JMenu("File");
        private JMenu quitMenu = new JMenu("Quit");
        private JMenuItem selectChoice = new JMenuItem("Select");
        private JMenuItem runChoice = new JMenuItem("Run");
        private JMenuItem reallyQuitChoice = new JMenuItem("Really quit");
        private JMenuItem cancelChoice = new JMenuItem("Cancel");
        // declare an attribute to hold the chosen file
        private File chosenFile;
        // the constructor
        public textAnalyser()
            setTitle("Text Analyser"); // set title of the frame
            add(viewArea); // add the text area
            // add the menus to the menu bar
            bar.add(fileMenu);
            bar.add(quitMenu);
            // add the menu items to the menus
            fileMenu.add(selectChoice);
            fileMenu.add(runChoice);
            quitMenu.add(reallyQuitChoice);
            quitMenu.add(cancelChoice);
            // add the menu bar to the frame
            setJMenuBar(bar);
            // add the ActionListeners
    //        selectChoice.addActionListener(this);
    //        runChoice.addActionListener(this);
    //        reallyQuitChoice.addActionListener(this);
    //        cancelChoice.addActionListener(this);
            // configure the frame
            setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            setSize(450,200);
            setVisible(true);
         public void actionPerformed(ActionEvent e)
                   if(e.getSource() == displayContentsChoice)
                        try
                             final int MAX = 300;
                             FileReader textFile = new FileReader("textfile.txt");
                             BufferedReader textStream = new BufferedReader(textFile);
                             int ch; // holds integer value of character
                             char c; // holds character when type cast from integer
                             int counter = 0; //counts number of characters read
                             ch = textStream.read(); //reads the first character from the file
                             c = (char) ch; //type cast from integer to character
                             viewArea.append("\n");
                             /*     continue through the file until either the end of the file or the maximum
                             number of characters allowed have been read*/
                             while(ch != -1 && counter <= MAX)
                                       counter++; // increment the counter
                                       viewArea.append("" + c); // display the character
                                       ch = textStream.read(); // read the next character
                                       c = (char) ch;
                             textStream.close();
                             viewArea.append("\n");
                   catch(IOException ioe)
                             if(chosenFile == null) // no file selected
                                       viewArea.append("No file selected\n");
                             else
                                  viewArea.append("There was a problem reading the file\n");
    }          

    A couple of points:
    *You've commented out stuff that is needed, like the adding of actionlisteners, the implements actionlistener,...
    *Your actionlistener is looking for a menu choice which doesn't exist  "displayContentsChoice".  Does this menu item need to be created?
    *How much of this code have you yourself created?  Do you understand its inner working?
    *What is the purpose of this code?  Is it for work?  School?  Homework?
    Good luck!
    /Pete

Maybe you are looking for

  • Photoshop elements 11 Download Assistant

    I want to download the Adobe Download Assistant for photoshop Elements 11 Trial and the website to do this does not have a "Download" button.  Please help.

  • Publish iCal Local Account Calendar on OS X Server

    I'd like to publish my iCal calendar (iCal>Calendar>Publish...>Publish on: A private server) on my OS X Server 10.6.7 (). Whenever I attempt to do this using my local account on tthe server, I get the error: http://username@domain_name/Home.ics is no

  • SD_SALES_HEADER_MAINTAIN

    Hi All, Thanks in advance. can any one help me out to know why i am getting the error ' Error when copying the contract data in batch input ' when my program is calling the function module 'SD_SALES_HEADER_MAINTAIN'. I am getting subrc = 1 when contr

  • Why can't I access Adobe Media Encoder

    I have been successfully using all of the apps in Creative Cloud much of the time. However, there have been some inexplicable issues. My account is current. I just received that verification. When I try to launch Media Encoder this error message appe

  • AddChildAt / DEPTH ISSUE

    I'm burnt out badly with the display list....but Merry Xmas I created two display objects on the main timeline. One is the a loader Object to load my movies into. The second object (container) is a movieclip in the library. The problem is, the loader