I have hastable htmlcontent is html string of urlstring . I want to write hastable into a .text file .
Can anyone suggest a solution?
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();
}
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
.
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.
java.io.PrintWriter
API
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking
checkError()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With