因此,我试图通过保存对象来序列化数据以制作游戏。我已经本地化了将数据从流中写入和读取到单个类的位置,该类具有两个简单的方法来从文件中读取对象,并从文件中写入对象。我遇到的主要问题是我只是不知道如何获取要读取或写入的文件名,因此,每当我尝试调用这些方法时,它只是告诉我系统找不到指定的路径。即使当我打印出该方法找到的内容时,也会发生这种情况,它会产生与我可以在计算机中搜索的文件路径相同的文件路径。我不明白为什么系统找不到它。
public void SerializeObject(String file,Object obj) {
URL o = getclass().getResource(file);
String fileName = o.getPath();
System.out.println(fileName);
try {
FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
//fileOut.flush(); Does this clear current data in a file?
out.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
它将打印文件路径,然后告诉我找不到它:
/C:/Users/Aiden/eclipse-workspace/Platformer%20Game/bin/savedata/options_data/resolution.ser
java.io.FileNotFoundException: C:\Users\Aiden\eclipse-workspace\Platformer%20Game\bin\savedata\options_data\resolution.ser (The system cannot find the path specified)
我真的不明白为什么找不到文件。我还将这些代码拼凑在一起,因此,如果我不知道我处理该问题的方式是否普遍存在。
如何更改代码,以便系统识别文件路径?