4

我想将 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();
}
4

4 回答 4

11
// 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();
于 2012-10-21T08:42:44.863 回答
5

这会将字符串保存到 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 是可取的,因为否则它将使用操作系统使用的任何设置作为默认设置,这会给您带来兼容性问题。

于 2012-10-21T08:42:30.903 回答
1

像这样的东西:

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 结构编写的。但其他版本的想法也相同。

于 2012-10-21T08:46:51.137 回答
0

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

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);
}
于 2016-07-07T17:20:17.370 回答