4

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

Can anyone suggest a solution?

6 Answers 6

3

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();
}
3
  • This is a approuch for print a hastable, but i mean write hashtable into txt file i use BufferedWriter writer = new BufferedWriter(new FileWriter(resultOutputFile)); writer.write(googleHashTableResult); but it hava an error :erro The method write(int) in the type BufferedWriter is not applicable for the arguments
    – tiendv
    May 7, 2010 at 4:19
  • 1
    FileWriter is a subclass of OutputStreamWriter. BufferedWriter isn't. Don't pass in a BufferedWriter, pass in a FileWriter. If that isn't what you want, then adjust the code accordingly.
    – Edwin Buck
    May 7, 2010 at 4:54
  • Thanks for your reply I have approuch like you say ! Some thing like that OutputStreamWriter writer = new OutputStreamWriter(os); BufferedWriter buffer = new BufferedWriter(writer); for(Entry<String, String> obj: googleHashTableResult.entrySet()) { writer.write(obj.getKey()); writer.write(newline); writer.write(obj.getValue()); } writer.close(); buffer.close();
    – tiendv
    May 7, 2010 at 7:03
3

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

2
  • This will fail on a key that refers to a null entry with a NullPointerException. Remember, Maps have keys that refer to entries which may be null.
    – Edwin Buck
    May 7, 2010 at 4:56
  • Thanks for the update. Must be suffering from coding too defensively, which typically isn't a bad thing.
    – Edwin Buck
    May 7, 2010 at 20:00
1

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.

1

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.

1
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();
    }
  }
}
2
  • It have an erro The method write(int) in the type BufferedWriter is not applicable for the arguments (Hashtable<String,String>)
    – tiendv
    May 7, 2010 at 4:00
  • Oh, sorry. Updated the answer. May 7, 2010 at 4:29
1

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.

2
  • Ok thanks your reply. I have a question about jonson array. When i use google api to query a string and get the result. String serialized = JSONValue.toJSONString(yourMap); But when i show the result by Jeditor, it can't dislay the uicode (VietNamese ) but yahoo seach reult can . Show what is the encode of result of google seachengine ? and how can i dislay the result when it is vietnamese ?
    – tiendv
    May 7, 2010 at 12:48
  • tiendv, Sorry about the late answer. This is another question, you should one answer here and open a different question for this one. Cheers, May 21, 2010 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.