Results 1 to 3 of 3
  1. #1
    Arsenic is offline Member
    Join Date
    Mar 2009
    Location
    Atlantis
    Posts
    8
    Rep Power
    0

    Default [SOLVED] Read/Write to same XML file

    I wrote a program that uses a SAX parser to go through a document, replace a certain word with a user specified one, and then re-write it to the same file. The only problem is that I'm getting a

    "SAXParseException: Premature end of file.Error: null"
    error when I try to overwrite the current file.

    I have:
    FileReader file_in = new FileReader(arg[0]);
    theReader.parse(new InputSource(file_in));
    in my main program

    but then in my actual parser class in order to write to the file I have
    BufferedWriter out = new BufferedWriter(new FileWriter(filename,false));

    I assumed that by giving the FileWriter the flag to overwrite that everything should work, alas I was wrong. The program works as it should if I do something like:
    String newFile = "NEW" + filename;
    and then pass it to FileWriter, but when it's reading/writing to the same file, it freaks out.

    Any suggestions?

  2. #2
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    10

    Default

    You can't read and write to the same file at the same time, unless you use a RandomAccessFile. You have to close the Reader before you open the Writer.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  3. #3
    Arsenic is offline Member
    Join Date
    Mar 2009
    Location
    Atlantis
    Posts
    8
    Rep Power
    0

    Default

    Whoops! Quite right! Forgot the start/end functions were actually during the parse. Heh, I feel s.m.r.t.

    Thanks Orange. :]

Similar Threads

  1. [SOLVED] write&read a binary file
    By tOpach in forum New To Java
    Replies: 9
    Last Post: 05-01-2009, 01:28 AM
  2. Replies: 5
    Last Post: 02-05-2009, 11:28 AM
  3. Replies: 5
    Last Post: 01-20-2009, 10:08 AM
  4. Read and Write file
    By mrdestroy in forum New To Java
    Replies: 13
    Last Post: 10-31-2008, 01:11 PM
  5. File read/write problems
    By p900128 in forum New To Java
    Replies: 4
    Last Post: 06-27-2008, 01:15 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •