我想在 txt 文件中写入和读取此哈希映射。这是我尝试过的:
主类:
SaveRead xd = new SaveRead();
HashMap <String,Integer>users = new HashMap<String,Integer>();
启动时调用//e
private Object e() throws ClassNotFoundException, FileNotFoundException, IOException {
return xd.readFile();
}
public void onFinish() {
try {
xd.saveFile(users);
} catch (IOException e) {
}
}
保存阅读类:
public class SaveRead implements Serializable{
public void saveFile(HashMap<String, Integer> users) throws IOException{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("/Users/Konto/Documents/scores.txt"));
outputStream.writeObject(users);
}
public HashMap<String, Integer> readFile() throws ClassNotFoundException, FileNotFoundException, IOException{
Object ii = new ObjectInputStream(new FileInputStream("/Users/Konto/Documents/scores.txt")).readObject();
return (HashMap<String, Integer>) ii;
}
}
这看起来可以吗?当它尝试读取文件时,我没有得到想要的结果。有没有更好的方法?
这可能是因为您没有关闭流,所以内容没有刷新到磁盘。您可以使用 try-with-resources 语句(在 Java 7+ 中可用)来清理此问题。下面是一个可编译的示例:
public class SaveRead implements Serializable
{
private static final String PATH = "/Users/Konto/Documents/scores.txt";
public void saveFile(HashMap<String, Integer> users)
throws IOException
{
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH))) {
os.writeObject(users);
}
}
public HashMap<String, Integer> readFile()
throws ClassNotFoundException, IOException
{
try (ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH))) {
return (HashMap<String, Integer>) is.readObject();
}
}
public static void main(String... args)
throws Exception
{
SaveRead xd = new SaveRead();
// Populate and save our HashMap
HashMap<String, Integer> users = new HashMap<>();
users.put("David Minesote", 11);
users.put("Sean Bright", 22);
users.put("Tom Overflow", 33);
xd.saveFile(users);
// Read our HashMap back into memory and print it out
HashMap<String, Integer> restored = xd.readFile();
System.out.println(restored);
}
}
编译并运行它在我的机器上输出以下内容:
{Tom Overflow=33, David Minesote=11, Sean Bright=22}