我想將包含 UTF-8 數(shù)據(jù)的對象存儲到文件中。不幸的是,我嘗試過的一切都沒有奏效。我真的很感激你的建議。我的代碼看起來像這樣: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 字符,否則此解決方案適用于所有情況。
Java 存儲帶有 UTF 8 字符的對象
慕尼黑8549860
2021-07-13 17:01:04