我需要将哈希图的数组列表保存到外部文件中。我可以对文本文件使用任何格式,因为程序设置为忽略文本文件(特别是任何带有.txt
扩展名的文件)。哈希图非常简单,只是带有这些单词计数的单词。存储它的理想文件格式是什么?
问问题
840 次
2 回答
6
你可以使用java.util.Properties
.
Properties properties = new Properties();
properties.putAll(yourMap); // You could also just use Properties in first place.
try (OutputStream output = new FileOutputStream("/foo.properties")) {
properties.store(output, null);
}
您可以稍后阅读
Properties properties = new Properties();
try (InputStream input = new FileInputStream("/foo.properties")) {
properties.load(input);
}
// ... (Properties implements Map, you could just treat it like a Map)
也可以看看:
于 2012-10-15T23:43:01.523 回答
1
您可以使用序列化:
ObjectOutputStream stream = null;
try
{
File f = new File(filename);
stream = new ObjectOutputStream(new FileOutputStream(f));
stream.writeObject(your_arraylist);
}
catch (IOException e)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}
并在使用中阅读:
ObjectInputStream stream = null;
try
{
stream = new ObjectInputStream(new FileInputStream(f));
your_arrayList = (your_arrayList type here)stream.readObject();
}
catch (Throwable t)
{
// Handle error
}
finally
{
if (stream != null)
{
try
{
stream.close();
}
catch (Exception e) {}
}
}
于 2012-10-15T23:52:49.073 回答