tiendv
tiendv

Reputation: 2347

How to write a hashtable<string, string > in to text file,java?

I have hastable htmlcontent is html string of urlstring . I want to write hastable into a .text file .

Can anyone suggest a solution?

Upvotes: 4

Views: 18788

Answers (6)

Jonas Fagundes
Jonas Fagundes

Reputation: 1519

Since you don't have any requirements to the file format, I would not create a custom one. Just use something standard. I would recommend use json for that!

Alternatives include xml and csv but I think that json is the best option here. Csv doesn't handle complex types like having a list in one of the keys of your map and xml can be quite complex to encode/decode.

Using json-simple as example:

String serialized = JSONValue.toJSONString(yourMap);

and then just save the string to your file (what is not specific of your domain either using Apache Commons IO):

FileUtils.writeStringToFile(new File(yourFilePath), serialized);

To read the file:

Map map = (JSONObject) JSONValue.parse(FileUtils.readFileToString(new File(yourFilePath));

You can use other json library as well but I think this one fits your need.

Upvotes: 1

Enno Shioji
Enno Shioji

Reputation: 26882

import java.io.*;
class FileWrite 
{
   public static void main(String args[])
  {
    HashTable table = //get the table
    try{
        // Create file 
        BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
        writer.write(table.toString());
    }catch (Exception e){
        e.printStackTrace();
    }finally{
      out.close();
    }
  }
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533790

You can try

public static void save(String filename, Map<String, String> hashtable) throws IOException {
    Properties prop = new Properties();
    prop.putAll(hashtable);
    FileOutputStream fos = new FileOutputStream(filename);
    try {
       prop.store(fos, prop);
    } finally {
       fos.close();
    }
}

This stores the hashtable (or any Map) as a properties file. You can use the Properties class to load the data back in again.

Upvotes: 1

polygenelubricants
polygenelubricants

Reputation: 383966

For the I/O part, you can use a new PrintWriter(new File(filename)). Just call the println methods like you would System.out, and don't forget to close() it afterward. Make sure you handle any IOException gracefully.

If you have a specific format, you'd have to explain it, but otherwise a simple for-each loop on the Hashtable.entrySet() is all you need to iterate through the entries of the Hashtable.

By the way, if you don't need the synchronized feature, a HashMap<String,String> would probably be better than a Hashtable.

Related questions


Here's a simple example of putting things together, but omitting a robust IOException handling for clarity, and using a simple format:

import java.io.*;
import java.util.*;

public class HashMapText {
    public static void main(String[] args) throws IOException {
        //PrintWriter out = new PrintWriter(System.out);
        PrintWriter out = new PrintWriter(new File("map.txt"));

        Map<String,String> map = new HashMap<String,String>();
        map.put("1111", "One");
        map.put("2222", "Two");
        map.put(null, null);

        for (Map.Entry<String,String> entry : map.entrySet()) {
            out.println(entry.getKey() + "\t=>\t" + entry.getValue());
        }

        out.close();
    }
}

Running this on my machine generates a map.txt containing three lines:

null    =>  null
2222    =>  Two
1111    =>  One

As a bonus, you can use the first declaration and initialization of out, and print the same to standard output instead of a text file.

See also

Upvotes: 3

Edwin Buck
Edwin Buck

Reputation: 70949

How about one row for each entry, and two strings separated by a comma? Sort of like:

"key1","value1"
"key2","value2"
...
"keyn","valuen"

keep the quotes and you can write out keys that refer to null entries too, like

"key", null

To actually produce the table, you might want to use code similar to:

public void write(OutputStreamWriter out, HashTable<String, String> table)
throws IOException {
  String eol = System.getProperty("line.separator");
  for (String key: table.keySet()) {
    out.write("\"");
    out.write(key);
    out.write("\",\"");
    out.write(String.valueOf(table.get(key)));
    out.write("\"");
    out.write(eol);
  }
  out.flush();
}

Upvotes: 3

Alex Martelli
Alex Martelli

Reputation: 882541

For text representation, I would recommend picking a few characters that are very unlikely to occur in your strings, then outputting a CSV format file with those characters as separators, quotes, terminators, and escapes. Essentially, each row (as designated by the terminator, since otherwise there might be line-ending characters in either string) would have as the first CSV "field" the key of an entry in the hashtable, as the second field, the value for it.

A simpler approach along the same lines would be to designate one arbitrary character, say the backslash \, as the escape character. You'll have to double up backslashes when they occur in either string, and express in escape-form the tab (\t) and line-end ('\n); then you can use a real (not escape-sequence) tab character as the field separator between the two fields (key and value), and a real (not escape-sequence) line-end at the end of each row.

Upvotes: 1

Related Questions