我需要Java File IO操作方面的一些帮助。我试图将序列化对象附加到我的文件,但只有最后一个Object被附加到文件。 我已经尝试了很多建议,但还没有成功。 我怎么能做到这一点,请帮帮忙?
这是我的代码:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;
public class Working {
String FILENAME = "E:\\assignment\\userpass\\userpass.txt";
Scanner sc = new Scanner(System.in);
String sUser = null, sPass = null, sRole = null;
Signup signup = new Signup();
public void createUser(){
System.out.println(" Enter username: ");
sUser = sc.next();
System.out.println(" Enter password: ");
sPass = sc.next();
System.out.println(" Enter Role: ");
sRole = sc.next();
Working obj = new Working();
signup.setUsername(sUser);
signup.setPassword(sPass);
signup.setRole(sRole);
obj.serializeUser(signup);
}
public void serializeUser(Signup signup){
FileOutputStream fout = null;
ObjectOutputStream oout= null;
File file = new File(FILENAME);
try{
// fout = new FileOutputStream(file);
// fout = new FileOutputStream(file.getAbsoluteFile(), true);
fout = new FileOutputStream(file, true);
// fout = new FileOutputStream(FILENAME);
oout = new ObjectOutputStream(fout);
oout.writeObject(signup);
System.out.println("User has been serialized");
} catch(Exception e){
e.printStackTrace();
} finally {
if(fout != null){
try{
fout.close();
} catch(IOException e){
e.printStackTrace();
}
}
if(oout != null){
try{
oout.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
}
// for test purpose
public void showUsers(){
Working obj = new Working();
Signup add = obj.deserializeUser(FILENAME);
System.out.println(add);
}
// to show data
//test purpose
public Signup deserializeUser(String filename){
Signup userDetails = null;
File file = new File(FILENAME);
FileInputStream fin = null;
ObjectInputStream oin = null;
try{
fin = new FileInputStream(file);
oin = new ObjectInputStream(fin);
userDetails = (Signup) oin.readObject();
} catch(Exception ex){
ex.printStackTrace();
} finally{
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oin != null) {
try {
oin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return userDetails;
}
}
我已经在这里查了一下: 1. http://www.enseignement.polytechnique.fr/informatique/Java/1.8/java/io/FileOutputStream.html#FileOutputStream-java.lang.String-boolean- 2. Appending to an ObjectOutputStream
答案 0 :(得分:0)
您需要每次在循环周围创建一个新的Signup
对象,或者每次都调用ObjectOutputStream.reset()
,或者使用ObjectOutputStream.writeUnshared()
。
然而还有其他问题。
StreamCorruptedException
- 无效的类型代码AC'为什么不呢。您需要在第二个链接中使用该技术。