如何将 hashtable<string, string > 写入文本文件,java?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2786038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:49:23  来源:igfitidea点击:

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

javahashtable

提问by tiendv

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

我有 hastable htmlcontent 是 urlstring 的 html 字符串。我想将 hastable 写入 .text 文件。

Can anyone suggest a solution?

任何人都可以提出解决方案吗?

采纳答案by Alex Martelli

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.

对于文本表示,我建议选择一些不太可能出现在字符串中的字符,然后输出一个 CSV 格式的文件,其中包含这些字符作为分隔符、引号、终止符和转义符。本质上,每一行(由终止符指定,否则任一字符串中可能会有行结束字符)将具有作为第一个 CSV“字段”的哈希表中条目的键,作为第二个字段的值它。

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.

一种更简单的方法是指定一个任意字符,比如反斜杠\,作为转义字符。当它们出现在任一字符串中时,您必须将反斜杠加倍,并以转义形式表示制表符 ( \t) 和行尾 ( '\n);那么您可以使用一个真正的(非转义序列)制表符作为两个字段(键和值)之间的字段分隔符,并在每行的末尾使用一个真正的(非转义序列)行尾。

回答by Edwin Buck

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();
}

回答by polygenelubricants

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

对于 I/O 部分,您可以使用new PrintWriter(new File(filename)). 只需println像您一样调用方法System.out,然后不要忘记close()它。确保你IOException优雅地处理任何事情。

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

如果您有特定的格式,则必须对其进行解释,否则只需要一个简单的for-each循环就Hashtable.entrySet()可以遍历Hashtable.

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

顺便说一句,如果您不需要该synchronized功能, aHashMap<String,String>可能比 a 更好Hashtable

Related questions

相关问题



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

这是一个将事物组合在一起的简单示例,但IOException为了清晰起见省略了强大的处理,并使用了简单的格式:

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.txtcontaining three lines:

在我的机器上运行它会生成一个map.txt包含三行的文件:

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.

作为奖励,您可以使用 的第一个声明和初始化out,并将其打印到标准输出而不是文本文件。

See also

也可以看看

回答by Enno Shioji

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();
    }
  }
}

回答by Peter Lawrey

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.

这将哈希表(或任何 Map)存储为属性文件。您可以使用 Properties 类重新加载数据。

回答by Jonas Fagundes

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!

由于您对文件格式没有任何要求,因此我不会创建自定义格式。只需使用标准的东西。我建议使用 json !

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.

替代方案包括 xml 和 csv,但我认为 json 是这里的最佳选择。Csv 不处理复杂类型,例如在地图的键之一中有一个列表,而 xml 编码/解码可能非常复杂。

Using json-simpleas example:

json-simple为例:

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):

然后将字符串保存到您的文件中(使用 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.

您也可以使用其他 json 库,但我认为这个库适合您的需要。