At end of tether!  Reading in variables from a text file

Hi all
My stress factor has gone through the roof because I am trying to read in from a text file (you may have seen some earlir questions about ArrayLists) it's just not working!
The code is below. The result is that it's reading in all of the car data, none of the motorbike and only the first line for the services. It's odd and it's driving me insane!
Here's an example of the data it's reading. There are about 7-10 sets of data per type
<car><reg>AB04CDE</reg><make>Ford</make><model>Fiesta</model><colour>blue</colour><passenger_no>4</passenger_no></car>
<service><service_no>13570</service_no><reg>J605PLE</reg><date>15:07:2006</date><miles>20000</miles><part_replaced>brake_pads</part_replaced><part_replaced>front_tyres</part_replaced></service>
<motorbike><reg>TT05EKJ</reg><make>Triumph</make><model>Speedmaster</model><colour>black</colour><load>20.50</load></motorbike>
Here's the code
while (moreToRead) {
        String line;
        try {
          line = fileReader.getNextStructure();
// collect the data from the file
          if (line.indexOf("<car>")> -1){
            // Select/Extract the registration element
            int nStart = line.indexOf("<reg>");
            int nEnd = line.indexOf("</reg>");
            String reg = line.substring(nStart+5,nEnd);
            // Select/Extract the make element
            nStart = line.indexOf("<make>");
            nEnd = line.indexOf("</make>");
            String make = line.substring(nStart+6,nEnd);
            // Select/Extract the model element
            nStart = line.indexOf("<model>");
            nEnd = line.indexOf("</model>");
            String model = line.substring(nStart+7,nEnd);
            // Select/Extract the colour element
            nStart = line.indexOf("<colour>");
            nEnd = line.indexOf("</colour>");
            String colour = line.substring(nStart+8,nEnd);
            // Select/Extract the passenger_no element
            nStart = line.indexOf("<passenger_no>");
            nEnd = line.indexOf("</passenger_no>");
            String passenger_no = line.substring(nStart+14,nEnd);
            //convert string to int
            int passengerInt = Integer.parseInt(passenger_no);
            // declare new object car and assign the variables then add it to the array.
            Car c = new Car (reg, make, model, colour, passengerInt);
            carList.add(c);
  } else if (line.indexOf("<bike>")> -1) {
         // Select/Extract the registration element
         int nStart = line.indexOf("<reg>");
         int nEnd = line.indexOf("</reg>");
         String reg = line.substring(nStart+5,nEnd);
         // Select/Extract the make element
         nStart = line.indexOf("<make>");
         nEnd = line.indexOf("</make>");
         String make = line.substring(nStart+6,nEnd);
         // Select/Extract the model element
         nStart = line.indexOf("<model>");
         nEnd = line.indexOf("</model>");
         String model = line.substring(nStart+7,nEnd);
         // Select/Extract the colour element
         nStart = line.indexOf("<colour>");
         nEnd = line.indexOf("</colour>");
         String colour = line.substring(nStart+8,nEnd);
         // Select/Extract the load element
         nStart = line.indexOf("<load>");
         nEnd = line.indexOf("</load>");
         String load = line.substring(nStart+6,nEnd);
         //convert load string to double
         double bikeLoad = Double.parseDouble(load);
         // declare new object motorbike and assign the variables then add it to the array.
         Motorbike m = new Motorbike (reg, make, model, colour, bikeLoad);
         bikeList.add(m);
  } else  {
    // Select/Extract the service_number element
    int nStart = line.indexOf("<service_no>");
    int nEnd = line.indexOf("</service_no>");
    String service_no = line.substring(nStart+12,nEnd);
    console.println("service = " + service_no);
    nStart = line.indexOf("<reg>");
    nEnd = line.indexOf("</reg>");
    String reg = line.substring(nStart+5,nEnd);
    console.println("service = " + reg);
    nStart = line.indexOf("<date>");
    nEnd = line.indexOf("</date>");
    String date = line.substring(nStart+6,nEnd);
    console.println("service = " + date);
    nStart = line.indexOf("<miles>");
    nEnd = line.indexOf("</miles>");
    String miles = line.substring(nStart+7,nEnd);
    console.println("service = " + miles);
    nStart = line.indexOf("<part_replaced>");
    nEnd = line.indexOf("</part_replaced>");
    String part_replaced = line.substring(nStart+15,nEnd);
    console.println("service = " + part_replaced);
    //convert string to int
    int dateOfService = Integer.parseInt(date);
    //convert string to double
    double milesAtService = Double.parseDouble(miles);
    //convert service no to unique int
    int serviceNo = Integer.parseInt(service_no);
    // declare new object service and assign the variables then add it to the array.
    Service s = new Service (reg, part_replaced, serviceNo, dateOfService, milesAtService);
      serviceList.add(s);
      catch (Exception e) {
        // Run out of data
        moreToRead = false;
} If anyone can spy anything that could be causing this I love your advice. I simply can't see it.
Jo

hi jos,
we have been asked not to use a parser for this assignment. evil
tutor i think! lolYour example seems to imply that all the <tag> ... </tag> pairs have
to occur on a single line; if that is so, you can do some cheap
programming like this:String getText(String line, String tag) {
   int start= line.indexOf("<"+tag+">");
   int end= line.indexOf("</"+tag+">", start);
   if (start < 0 || end < 0) return null; // no <tag> ... </tag> pair found
   // return the text in between the <tag> ... </tag> tags
   return line.substring(start+tag.length()+2, end);
}kind regards,
Jos

Similar Messages

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

  • Reading parameters lists from a text file

    Hi All,
    Using CR XI R2 with VB6  and external .rpt files - - - - -
    In a VB6 app I use VB to loop through my tables to create dynamic parameter lists (CR XI is limited to the number of parameters it can create from the table). This works well but each time the user refreshes the report the same code is run to re-create the parameter list which is redundant and slows down the report(s).
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Thanks in advance!
    Peter Tyler
    Geneva - Switzerland

    I find this sentence confusing:
    Is it possible to manually create a series of text files - say each morning - and then read the parameter lists from the text file(s) at runtime instead of doing it on the fly each time?
    Typically, runtime means on the fly - I think...
    So, I'm not sure if you are trying to read a saved data report and filter that saved data so that you do not have to hit the database(?).
    Creating a text file is beyond the support of this forum, though that should be a trivial exercise. Reading a text file and passing the results to a parameter is the same thing you are doing already, so I'm not sure where the hang up would be here(?)
    Or - rather than creating a text file, why not create a temp table and query it as you do when you loop through the tables to create dynamic parameter lists(?).
    I'm pretty lost here...
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Reading signed interger from a text file:

    Is this possible with some construct in java? Attempting to read a signed number using .readInt() throws an exception before the first token is a malformed int. i,e, the sign + or -.
    I would like to read a signed integer from a text file but I am clueless.
    Any help is appreciated.

    It can be a bit of a dilemma for lexical analysers. Say you read "a + 12" then you'd generally want to process that as three separate lexemes. The monadic form of plus is less common than the monadic minus.
    A quick test shows that "+12" and "+ 12" are both rejected by Integer.parseInt() (which surprised me).
    I'd suggest if you want to read positive numbers then first analyse your input using a regular expression, for example "\\s*([-+]?)\\s*(\\d+)" followed by
    (matcher.match(1).equals("-") ? -1 : 1) * Integer.parseInt(matcher.match(2));Edited by: malcolmmc on May 24, 2010 2:10 PM

  • Reading in integers from a text file

    Hi, I am going to go for the 'reading in from a text file' action as I haven't done this before. So I have been looking at all the examples and am trying the one out below :) My question is that though the structure seems pretty straightforward, what is the action of the 'token' and why doesn't java recognise it as it is used in many different examples that I have seen?
    public static int[] getIntegersFromFile(String fileName) throws IOException {
                   StringWriter writer = new StringWriter();
                   BufferedReader reader = new BufferedReader(new FileReader(fileName));
                   List<Integer> list = new ArrayList<Integer>();
                   for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                   writer.write(line + " ");
                   StringTokenizer tokens = new StringTokenizer(writertoString());
                   while (tokens.hasMoreTokens()) {
                        String str = tokens.nextToken();
                        try {
                             list.add(new Integer(str));
                             } catch (NumberFormatException e) {
                                  System.out.println("Error '" + str + "' is not an integer.");
                   int[] array = new int[list.size()];
                        for( int i = 0; i < array.length; i++){
                        array[i] = list.get(i);
                   return array;
         }

    Hey, first of all, a piece of advice, try formatting your codes you make easier
    to understand for the people who help you. You can check out the
    formatting tips
    Now, A think that could help you a lot, is the next link, seek out the
    documentation for the StringTokenizer class
    http://java.sun.com/j2se/1.5.0/docs/api/
    Here your code formated and later my interpretation of your question.
    public static int[] getIntegersFromFile(String fileName) throws IOException {
       StringWriter writer = new StringWriter();
       BufferedReader reader = new BufferedReader(new FileReader(fileName));
       List<Integer> list = new ArrayList<Integer>();
       for (String line = reader.readLine(); line != null; line = reader.readLine()) {
          writer.write(line + " ");
       StringTokenizer tokens = new StringTokenizer(writertoString());
       while (tokens.hasMoreTokens()) {
          String str = tokens.nextToken();
          try {
             list.add(new Integer(str));
          } catch (NumberFormatException e) {
             System.out.println("Error '" + str + "' is not an integer.");
       int[] array = new int[list.size()];
       for( int i = 0; i < array.length; i++){
          array = list.get(i);
       return array;
    }StringTokenizer separates the string contained by the space character, and
    each piece of the separated string is stored into the token.
    Further on, could you extend your question about "why doesn't Java
    recognize what?" please, because I don't know if you have a problem
    iterating or is just that it doesn't compile or what.
    Expecting your answer, to complete mine, cya around.
    -Best Regards.

  • How to read some records from a text file into java(not all records)

    hello,
    how to read text files into java. i need only few records from the text file not all records at a time.
    If any one knows plz reply me
    my id is [email protected]

    this snipet reads a text file line by line from line 1 to 3
    try {
                  FileReader fr = new FileReader(directory);
                  BufferedReader br = new BufferedReader(fr);
                  int counter = 0;
                  while ((dbconn = br.readLine()) != null) {
                      switch(counter){
                          case 0:
                            status = dbconn;
                          break;
                          case 1:
                            userName = dbconn;
                          break;
                          case 2:
                            apword = dbconn;
                          break;
                      counter++;
                  br.close();
        }catch(IOException e){
        }

  • Read specified line from a text file

    Hi,
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?
    Thanks and regards,
    Krt_Malta

    Krt_malta wrote:
    I am trying to read a specific line from a text file. I don't want to read all of it but just this specific line... say line number 2. Is there a method built-in in java or should I code this myself?Is there anything in your use case that precludes using the offset of the start of the line rather than the line number?

  • Read email adress from a text file then check the validity of them

    a text file has three lines, each line contains one email adress:
    [email protected]
    qwe@@ws.com
    wer//@we.net
    read the email address from a text file, then check which one is invalid, output the invalid email adress in the console.

    no 3 .umm, an email adress can have more than 2 '.'s in it,
    example:
    [email protected]
    would be a valid email address.
    To decide what a valid address is you'd need to parse it against the correct standard.
    I think however that javax.mail.internet.InternetAddress does this for you, check out the docs:
    http://java.sun.com/products/javamail/1.2/docs/javadocs/javax/mail/internet/InternetAddress.html
    even if it parses it may not be a valid address though in that it may not actually exist.

  • Reading variables from a text file into a flash projector exe

    I am using Flash CS4 and my script is in ActionScript2.
    I am developing a flash projector file that runs when a user puts in a cd to guide them through the steps they need to install a program and then kicks off the installer.
    I use fscommand to run a utility that reads the users registry to determine the PCs regional settings and then writes this to a text file in the users %temp% directory.
    I then use the LoadVariablesNum command to read in the text file and get the variables.
    This was working fine when I had the text file stored in a different directory, but when I try and refer to the %temp% directory, I get an Error opening file message.
    Is there anyway to get flash to look in the %Temp% directory?
    Thanks in advance,
    Carol Lutz

    Code-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
    ******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
        for(int x = 0; x < maze.length; x++) {
            if (input.hasNextLine()) {
                String insert = input.nextLine();
                maze[x] = insert.charAt(x);
    }Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
        if (input.hasNextLine()) {
            String insert = input.nextLine();
            for(int x = 0; x < insert.size(); x++) {
                maze[i][x] = insert.charAt(x);
    }Otherwise, only one character per line is read and storing a character actually should fail.

  • To read structure variable from a binary file

    Hi Everyone,
    Iam having a binary file created by c++.It contains structure  like this one...
    struct
          char name[2];
          unsigned short num;
          char identity[4];
          double date;
          union
              byte id[4];
              int sizeconst;
              int size;
    I want to read this struct file in labview. How can i do that?

    Once I had the same problem, I've asked NI-support and they said to me because of different kind of reading method that that operation is impossibile to do, so the solution to solve the problem has been to create a C++ library that reads the structure from the file and makes disponible the data. After, I've called the library by "Call by library function" in my Labview software.
    Ricky
    Italian Developer engineer
    www.www.selt-sistemi.com

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

Maybe you are looking for