1

I'm new In java and I have a program that writes information on txt file, the only problem I seem to have Is that if the fileWriter is appending the file I can't edit, or rewrite a specific line on the file, Is there any way to set the writer to start at the start of the file instead of the end without erasing the data? Because in that way I can't edit the info inside the file. Thanks in advance for any answer!

Shahar Kazaz
  • 37
  • 1
  • 6
  • post some of your code. – Makky Jul 04 '13 at 14:09
  • Give some context so we can help. Some code, may be pseudo-code? – zEro Jul 04 '13 at 14:12
  • 2
    Possible duplicate: http://stackoverflow.com/questions/822150/modify-a-txt-file-in-java – joe776 Jul 04 '13 at 14:13
  • Isn't there any way to do this without having to make a temporary file and coping all of the original file? And yes the link you posted is what I mean, my code only contains a BufferdWriter constracor nothing else . That appends the txt file, but when I do try to write something it starts at the end of the file – Shahar Kazaz Jul 04 '13 at 14:19

1 Answers1

0

The FileWriter class has a couple of constructors. Some of them with an "append" parameter of type boolean. Did you use one of those constructors with true?

You should use false for that parameter.

    /**
 * Constructs a FileWriter object given a File object. If the second
 * argument is <code>true</code>, then bytes will be written to the end
 * of the file rather than the beginning.
 *
 * @param file  a File object to write to
 * @param     append    if <code>true</code>, then bytes will be written
 *                      to the end of the file rather than the beginning
 * @throws IOException  if the file exists but is a directory rather than
 *                  a regular file, does not exist but cannot be created,
 *                  or cannot be opened for any other reason
 * @since 1.4
 */
public FileWriter(File file, boolean append) throws IOException {
    super(new FileOutputStream(file, append));
}
user573215
  • 4,679
  • 5
  • 22
  • 25
  • But that way all of the data that the file had would be deleted and that's not what I want – Shahar Kazaz Jul 04 '13 at 14:20
  • 1
    I think you have to rewrite the file completely from the beginning to the end with updated data. At least I don't know any way to just update a line or something in the middle of a file. IIRC there is no such way (at least in Java). You should also read the question linked abhove as possible duplicate. – user573215 Jul 04 '13 at 14:29