Error when reading and writing a line from a text file - any help!!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 15 of 15

Thread: Error when reading and writing a line from a text file - any help!!

Hybrid View

  1. #1
    Join Date
    Nov 2005
    Posts
    44

    Error when reading and writing a line from a text file - any help!!

    Hi,

    My test main class allows user input to create one integer, which I've converted to a string, plus four strings representing details to be written to a file. When these details are written to the file they initially read correctly, eg:

    111,hello one,hello two,hello three,hello four


    The problem occurs when I try to write a second set if user entry values to this file. It is expecting four strings as words, and therefore reads and writes the above line as follows,

    111,,hello,one,hello,two,hello,three,hello


    I have absolutely no idea why this is happening and would really appreciate some help or advice with this problem.

    The current code for my test main class is as follows,

    Code:
     
    import simplejava.*;
    import videos.*;
    import java.io.*;
     
    public class AddTitle {
        
        public static void main(String[] args) {
            String film, actor1, actor2, director, title;
            int codeNum;
            
            SimpleReader keyboard = new SimpleReader();
            SimpleWriter screen = new SimpleWriter();
            
            SimpleReader inFile = new SimpleReader("title_test.txt");
            
            TitleList titles = new TitleList(inFile);
            codeNum = keyboard.readInt("Title Code for the Film");
            int intValue = codeNum;
            String stringValue = Integer.toString(intValue);
            film = keyboard.readLine("Film Title?");
            actor1 = keyboard.readLine("Lead Actor?");
            actor2 = keyboard.readLine("Supporting Actor?");
            director = keyboard.readLine("Director?");
            titles.add(new Title(codeNum, film, actor1, actor2, director));
            screen.println(titles);
            
            title = inFile.readLine();
            String[] myStrings = title.split(",");
            for (int i=0; i<myStrings.length; i++)
            System.out.print(myStrings[i]);
            
            SimpleWriter outFile = new SimpleWriter("title_test.txt");
            titles.saveTo(outFile);
            outFile.close();
        }
    }
    Does anybody know why this is happening?

    Any help or advice really appreciated!!

  2. #2
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Can you postulate an explanation?

    Is this an artifact of the SimpleReader class you are using?

    Do the added titles and information print out to the screen properly with your screen.print() method call? If so, then it seems there is a problem in the structure of your file which is being read back into the part of your code before your System.out.println() call.

    What does the stored copy of your file look like? Try writing to disk before you do your System.out.println() segment, close the stream, then re-open to do the last bit ...

  3. #3
    Join Date
    Nov 2005
    Posts
    44

    Re: Error when reading and writing a line from a text file - any help!!

    Hi,

    When a user adds the first set of details, it prints to the screen and also saves perfectly. It is only subsequent prints and saves that don't work correctly. When the user inputs the second set of data, this new data is printed out and saved correctly, but the previous input data gets rewritten as follows,

    Original input = hello world, hello world2, hello world3, hello world4
    subsequent saves = hello,world,hello,world2,hello,world3,hello,world4

    I think basically the problem is with the constructors in the Title class, which require four Strings, read using readWord(). Whereas, the only way I know to allow a user to input more than one word on a line via the keyboard is using readLine() in the test main class.

    Does anyone know how to correct this possible conflict?

    The output to the test file saves as follows after the first run and save,
    Code:
    20 1
    111,film one,actor one,actress one,director one
    and then it is changed and outputs as follows with the errors,
    Code:
    20 2
    111,,film,one,actor,one,actress,one,director
    112,film two,actor two,actress two,director two
    The console put put also changes as well with errors as follows,
    Code:
    Borrower Count =  2 Max Borrowers = 20
    Code Number = 111 Film = ,film Lead Actor = one,actor Supporting Actor = one,actress Director = one,director 
    Code Number = 112 Film = film two Lead Actor = actor two Supporting Actor = actress two Director = director two 
    one
    Any help or advice gratefully appreciated!!

  4. #4
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    A difficulty in reading your code is that you have thrown all your code into one body, rather than having the modules separated (separation of concerns).

    Your postulation sounds to be accurate, to me. When you "readWord()", you are reading only to whitespace. When you "readLine()", you read to a linefeed or newline character. So if you are reading from the data written to disk using the objects created using the constructor methods you mention, you have not grabbed all of the content intended for each of the data members - you've only grabbed one word ...

    Sounds like you need to go back to your constructor.

    Remember you need to flush or perform an extra "readLine" (whose content gets dumped) after grabbing an int or anything shorter than a full line - you have not grabbed the newline character, and that is why you are getting the empty string followed by a comma.
    Last edited by nspils; 11-28-2005 at 04:47 PM.

  5. #5
    Join Date
    Nov 2005
    Posts
    44
    Hi,

    I've implemented a conversion of the strings to one string to hopefully solve this problem, but I now get the following error,
    Code:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
            at VideoStoreProject.Title.<init>(Title.java:21)
            at VideoStoreProject.AddTitle.main(AddTitle.java:40)
    Java Result: 1
    These errors refer to the following code. Firstly within the Title class,
    Code:
    public Title(int Title, String filmDetails) {
            titleCode = Title;
            String[] words = filmDetails.split(",");
            filmName = words[0];
            leadActor1 = words[1];//this is the line causing the above error at line 21
            leadActor2 = words[2];
            director = words[3];
        }
    and secondly within the main class,
    Code:
    titles.add(new Title(codeNum, videoTitles));//line causing the second error
    I have written a saveTo method in the Title class, which is supposed save the file with commas aswell. The code is as follows,
    Code:
    public void saveTo(SimpleWriter out) {
            out.println(titleCode+","+filmName+","+leadActor1+","+leadActor2+","+director);
        }//saveTo method writes details of the Title class to a text file
    Can anybody see a reason why this method would not now write the correct file with the commas aswell?

    Any help gratefully appreciated!

  6. #6
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    It it my recollection, reinforced by a look at the API documentation on the split() method, that you must use a "regex pattern" to do the search - so try using "\," as your "string" for the split delimiter.

    Or, think about using the Scanner class.

  7. #7
    Join Date
    Nov 2005
    Posts
    44
    No luck. It produces an error 'illegal escape character' if you use "\,"

    This is really starting to annoy me.

    All I'm trying to do is allow user input within the main class to add one integer and four strings(each of which can be any number of words on a line), save them as a comma seperated list and then be able to repeat this as many times as possible, including reading in existing records and add new ones.

    I really don't see why this should be so hard.

  8. #8
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    Try two backslashes ... it has been a while since I've done this and it's rusty ...

    you can generate the Pattern directly or do some research on how best to represent the comma using "escape code structure"

  9. #9
    Join Date
    Nov 2005
    Posts
    44
    Hi,

    I'm pleased to say that I've corrected the above error, by simply adding the commas directly to the titles.add method in the main class. It has staring me right in the face for hours.

    However, on the third time the user tries to save the data, the previous line in the data is saved as follows,
    Code:
    111,,film title, actor one, actor two, director
    What did you mean you when you said you had to flush after inputting an integer?

    Any adive or help gratefully appreciated??

  10. #10
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    You are calling "readInt()" to get the integer, so you are getting the content (because it is reading up to the white space) but leaving behind the new line marker. You need to get rid of the new line marker from your input stream so that when you do your first readLine() you are at the start of a new line.

  11. #11
    Join Date
    Nov 2005
    Posts
    44
    Quick correction - I meant to say I added the commas directly to
    Code:
    String videoTitles = ....
    in the main class.

    Sorry for the confusion!

  12. #12
    Join Date
    Nov 2005
    Posts
    44
    Hi,

    Thanks for the reply. I've found the flush method, but it only applies to the outFile. How do I apply this to flushing the integer prior to the first String?

    I have no idea how to implement your previous suggestion. Do you have any sample code?

    Thank you for all your help so far!!

  13. #13
    Join Date
    Dec 2004
    Location
    San Bernardino County, California
    Posts
    1,468
    you're calling flush (or readLine()) on the instream.

  14. #14
    Join Date
    Nov 2005
    Posts
    44
    Hi,

    Thanks for the reply. I've tried flushing or removing the NewLine character after the readInt(), using
    Code:
    String remove = keyboard.readLine();
    but I still get the same problem with the output. The file is written as follows,
    Code:
    Code Number = 111 Film = forrest gump Lead Actor = tom hanks Supporting Actor = gary sinise Director = robert zemeckis 
    Code Number = 112 Film =  Lead Actor = moulin rouge Supporting Actor = nicole kidman Director = ewan mcgregor 
    Code Number = 113 Film =  Lead Actor = lost in translation Supporting Actor = bill murray Director = scarlett johansson
    It appears as though each time the file is read and then rewritten, it is moving the first string to the second string position in the list, and so on.

    I really don't understand why this is happening.

    Does anybody have any ideas what might be causing this?

  15. #15
    Join Date
    Nov 2005
    Posts
    44
    Hi,

    I'm pleased to say the problem has now been solved. I've added some extra code to my split method in the first constructor within the Title class. It now works as required. Code is as follows,
    Code:
    String[] words = filmDetails.replaceFirst("\\A,","").split(",");
    Thank you to everyone for their help and advice!

Similar Threads

  1. Reading and Writing to a file
    By Fergy25 in forum Java
    Replies: 1
    Last Post: 11-14-2005, 05:28 PM
  2. writing to a text file - VB 6 Please Help
    By sameera in forum VB Classic
    Replies: 1
    Last Post: 09-16-2005, 06:42 AM
  3. Reading and writing lines from a text file...
    By Jenks in forum VB Classic
    Replies: 6
    Last Post: 05-24-2005, 03:22 PM
  4. Replies: 3
    Last Post: 08-23-2001, 12:01 PM
  5. NullPointerException when reading text file
    By Andrew McLellan in forum Java
    Replies: 3
    Last Post: 05-09-2001, 06:34 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center