2

I have files in who I need to record serialized object. I open ObjectOutputStream for writing in files. If I didn't wrote nothing in file, file content get deleted. I don't want content to be deleted when I make ObjectOutputStream.

My code (I use Guice),

@Provides
@ArticleSerializationOutputStream
public ObjectOutputStream getArticleObjectOutputStream(Config config) {
  ObjectOutputStream out = null;
  String fileName = config.getConfigValue(ARTICLE_SNAPSHOT);
  try {
    out = new ObjectOutputStream(new FileOutputStream(new File(fileName)));
  } catch (IOException e) {
    String errorMessage = String.format(IO_EXCEPTION_PROBLEM, fileName);
    addError(errorMessage);
  }
  return out;
}
Sam
  • 7,252
  • 16
  • 46
  • 65

2 Answers2

13

Creating the ObjectOutputStream itself won't overwrite anything. I suspect you just created a new FileOutputStream which will have truncated any current content unless you tell it to append. I think you want:

FileOutputStream fos = new FileOutputStream(filename, true);

to make it append to a file instead of overwriting.

EDIT: Yes, as per your edit, you're creating a new FileOutputStream without telling it to append. It's therefore overwriting the file.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

I solve the problem. I use provider instead instancing the OutputStrams in begin with Guice.

@Inject @ArticleOutputStream
Provider<OutputStream> articleObjectOutputStream;

articleOutputStream.get();

Work fine for now.

Hkachhia
  • 4,463
  • 6
  • 41
  • 76