use*_*988 4 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();
}
Run Code Online (Sandbox Code Playgroud)
avi*_*iad 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();
Run Code Online (Sandbox Code Playgroud)
这会将字符串保存到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();
}
}
Run Code Online (Sandbox Code Playgroud)
特别需要选择UTF-8,因为否则它将使用操作系统使用的默认设置作为默认设置,这将给您带来兼容性问题。