Reputation: 7879
I need to save an arraylist of hashmaps to an external file. I can use any format expect for a text file, because the program is set to ignore text files (specially, anything with a .txt
extension). The hashmaps are pretty straightforward, just words with counts of those words. What is the ideal file format to store this in?
Upvotes: 1
Views: 1015
Reputation: 679
You could use serialization:
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) {}
}
}
And read it in using:
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) {}
}
}
Upvotes: 1
Reputation: 1108922
You could use 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);
}
You can read it later by
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)
Upvotes: 6