0

possible duplicate : Java: How to read a text file

this is my code:

this.fileMetaDataPrintWriter = 
new PrintWriter(new FileOutputStream(new File(fileName), false));

and in other method

fileMetaDataPrintWriter.write(somedata);

these both methods are called in a thread and the filehandle closed when thread exits.

Still my file is appended and not overwritten.

what is the mistake?

Community
  • 1
  • 1
user1079065
  • 2,085
  • 9
  • 30
  • 53
  • 4
    This code does not append to the file. Either this isn't the real code or you have other code that does append to it. – user207421 Mar 24 '15 at 03:24

1 Answers1

1

I have verified that the following code snippet written directly in main method is overwriting the file contents. Perhaps it is some other interaction in code that is causing a different behavior for you? Test this snippet and verify if overwrite works correctly

PrintWriter fileMetaDataPrintWriter = new PrintWriter(new FileOutputStream(new File("appendtest.txt"), false), true);
fileMetaDataPrintWriter.write("This replaces contents of appendtest.txt");
fileMetaDataPrintWriter.close();
vsnyc
  • 2,117
  • 22
  • 35
  • The `flush()` is redundant before `close().` – user207421 Mar 24 '15 at 03:49
  • Autoflush has nothing to do with it. `flush()` is *always* redundant before `close().` – user207421 Mar 24 '15 at 22:08
  • I understand, I would normally use `try-with-resources` construct or put the `close()` in a finally block. Auto `flush()` is my choice if I want to tail the file while it's being written – vsnyc Mar 24 '15 at 23:53