如何将HashSet <string>保存为.text?</string>

时间:2012-10-21 08:28:46

标签: java string file-io set hashset

我想将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 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:4)

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

答案 2 :(得分: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构造编写的。但是对于其他版本,这个想法也将保持不变。

答案 3 :(得分: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);
}