我想在txt文件中写入和读取这个hashmap。这就是我的尝试:
主要课程:
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) {
}
}
// SaveRead类:
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;
}
}
这看起来好吗?当它尝试读取文件时,我没有得到所需的结果。有没有更好的方法呢?
答案 0 :(得分:3)
可能是因为您没有关闭流,因此内容不会刷新到磁盘。您可以使用try-with-resources statement(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}