我想将包含 UTF-8 数据的对象存储到文件中。不幸的是,我尝试过的一切都没有奏效。我真的很感激你的建议。我的代码看起来像这样:
public static void saveData(MyClass myData) {
try (FileOutputStream fs = new FileOutputStream("data.ser");
ObjectOutputStream os = new ObjectOutputStream(fs)) {
ArrayList<MyClass> dataOld = new ArrayList<>();
ArrayList<MyClass dataNew = getData();
for (int i = 0; i < dataOld.size(); i++) {
dataNew.add(dataOld.get(i));
}
dataNew.add(myData);
os.writeObject(dataNew);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<MyClass> getData() {
ArrayList<MyClass> data= null;
try (FileInputStream fi = new FileInputStream("data.ser"); ObjectInputStream os = new ObjectInputStream(fi)) {
data= (ArrayList<MyClass>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return data;
}
除非我在对象中存储 UTF 8 字符,否则此解决方案适用于所有情况。
相关分类