Reputation: 177
I'm trying to create a system where users can save a series of Message objects to a .txt file, which can then be de-serialized and read by the recipient of the Message. However each time I try and write to the file I simply overwrite the object that was there previously.
My current code is as follows:
public class Comms{
Message msg;
public void sendMessage(Message myMessage){
msg = myMessage;
//Generate Message ID
String msgID = "MSG" + genMsgID();
myMessage.setMessageID(msgID);
//********************************************************
try
{
FileOutputStream logFile = new FileOutputStream("logFile.txt");
NoHeaderObjectOutputStream out = new NoHeaderObjectOutputStream(logFile);
out.writeObject(myMessage);
out.close();
logFile.close();
}catch(IOException i)
{
}
}
}
class NoHeaderObjectOutputStream extends ObjectOutputStream {
public NoHeaderObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
protected void writeStreamHeader() {}
}
I appreciate that there are similar questions out there but with my limited knowledge I'm struggling to make sense of the answers provided.
If anyone has a solution to this or some pointers that'd be greatly appreciated.
Upvotes: 1
Views: 2265
Reputation: 2803
You can store your objects in a collection type which is serializable. Like one of the many List implementations such as ArrayList. Then you serialize the collection. Deserializing the collection back into a List, and adding and removing as you see fit.
Or alternatively, you could store each object in its own file.
Here is a quick example:
package arg;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Serialization {
private static final String FILE_NAME = "test.dat";
private static ArrayList<Name> names;
public static void main(String[] args) {
Serialization s = new Serialization();
s.start();
}
private void start() {
loadFile();
promptForName();
}
private void promptForName() {
String input = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while (!input.equals("Exit")) {
System.out.println("Press 1 to enter new name.\r\nPress 2 to save.\r\nPress 3 to display.\r\nType Exit to exit.");
input = br.readLine();
if (input.equals("1")) {
System.out.println("Enter a name");
input = br.readLine();
Name n = new Name();
n.name = input;
names.add(n);
}
else if (input.equals("2")){
saveFile();
}
else if (input.equals("3")){
for (Name n : names) {
System.out.println(n.name);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveFile() {
File f = new File(FILE_NAME);
f.delete();
try {
f.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))){
oos.writeObject(names);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void loadFile() {
File f = new File(FILE_NAME);
if (f.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f)))
{
names = (ArrayList<Name>) ois.readObject();
} catch (IOException e) {
f.delete();
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
f.delete();
}
}
else
{
names = new ArrayList<Name>();
}
}
private static class Name implements Serializable {
public String name;
}
}
Edit - Your code sorta came after the answer. If this is for logging purposes you should use log4j or some similar ready made logging API.
Upvotes: 2
Reputation: 44844
Look at http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String, boolean)
and you will see that the FileOutputStream
constructor has an append option.
Upvotes: 2