我对此代码有疑问:
public class DataController {
DataController() {}
Wallet getWallet(String name){
ObjectInputStream ois;
File file = new File(FileSystemView.getFileSystemView().getDefaultDirectory(), "wallets/" + name);
Wallet wallet;
try {
ois = new ObjectInputStream(new FileInputStream(file));
wallet = (Wallet) ois.readObject();
ois.close();
return wallet;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
void save(Wallet wallet){
ObjectOutputStream oos;
File file = new File(FileSystemView.getFileSystemView().getDefaultDirectory(), "wallets/wallet" + wallet.getName() + ".txt");
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
if (!file.exists()) {
oos.writeObject(wallet);
}
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String[] listWallets(){
File file = new File(FileSystemView.getFileSystemView().getDefaultDirectory(), "wallets");
if (file.exists() && file.list().length > 0) {
return file.list();
} else {
return new String[]{"No wallets"};
}
}
}
当我调用save方法时,它应该在文件中序列化我的Wallet对象,但它会写出奇怪的字符(Ԁ)。我不指望出了什么问题。有没有人查看错误是什么?
我的钱包课程:
package fr.paragoumba.mywallet;
import java.io.Serializable;
public class Wallet implements Serializable {
Wallet(String name) {
this.name = name;
}
public String toString(){
return "Nom : " + name + "\nFonds : " + founds;
}
}
答案 0 :(得分:0)
除了ObjectOutputStream
标题外,您不能序列化任何内容。
oos = new ObjectOutputStream(new FileOutputStream(file));
创建file
,或者抛出IOException
。
if (!file.exists())
所以这绝不是假的。
oos.writeObject(wallet);
所以这永远不会执行。很奇怪的代码。你为什么要写一个不存在的文件?
oos.close();
由于您没有在文件中写入任何其他内容,如果您尝试从中读取对象,则会获得EOFException
。