【问题标题】:Howto save HashSet<String> to .txt?如何将 HashSet<String> 保存到 .txt?
【发布时间】:2012-10-21 08:28:46
【问题描述】:

我想将 HashSet 存储到服务器目录。 但我现在只能将其存储在 .bin 文件中。 但是如何将 HashSet 中的所有 Key 打印到 .txt 文件中呢?

static Set<String> MapLocation = new HashSet<String>();

    try {
        SLAPI.save(MapLocation, "MapLocation.bin");
    } catch (Exception ex) {

    }

public static void save(Object obj, String path) throws Exception {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
            path));
    oos.writeObject(obj);
    oos.flush();
    oos.close();
}

【问题讨论】:

  • 为什么不遍历集合并将所有字符串写入文件?另外,SLAPI 是什么类型的对象?
  • HashSet 中的键是什么意思?

标签: java string file-io set hashset


【解决方案1】:
// check IOException in method signature
BufferedWriter out = new BufferedWriter(new FileWriter(path));
Iterator it = MapLocation.iterator(); // why capital "M"?
while(it.hasNext()) {
    out.write(it.next());
    out.newLine();
}
out.close();

【讨论】:

  • 非常感谢,它完成了这项工作。
【解决方案2】:

这会将字符串保存到 UTF-8 文本文件:

public static void save(Set<String> obj, String path) throws Exception {
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(
            new OutputStreamWriter(new FileOutputStream(path), "UTF-8"));
        for (String s : obj) {
            pw.println(s);
        }
        pw.flush();
    } finally {
        pw.close();
    }
}

特别选择 UTF-8 是可取的,否则它将使用操作系统使用的任何设置作为其默认设置,这会给您带来兼容性问题。

【讨论】:

    【解决方案3】:

    类似这样的:

    public static void toTextFile(String fileName, Set<String> set){
        Charset charset = Charset.forName("UTF-8");
        try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(fileName, charset))) {
            for(String content: set){
                writer.println(content);
            }
        } catch (IOException x) {
            System.err.format("IOException: %s%n", x);
        }
    }
    

    注意:此代码是使用 Java 7 中引入的 try-with-resource 结构编写的。但其他版本的想法也相同。

    【讨论】:

      【解决方案4】:

      避免文件末尾换行的另一种解决方案:

      private static void store(Set<String> sourceSet, String targetFileName) throws IOException
      {
          StringBuilder stringBuilder = new StringBuilder();
      
          for (String setElement : sourceSet)
          {
              stringBuilder.append(setElement);
              stringBuilder.append(System.lineSeparator());
          }
      
          String setString = stringBuilder.toString().trim();
          byte[] setBytes = setString.getBytes(StandardCharsets.UTF_8);
          Files.write(Paths.get(targetFileName), setBytes);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-02
        • 2021-07-14
        相关资源
        最近更新 更多