如何将Map对象写入文件 [英] How to write a Map object to a file
本文介绍了如何将Map对象写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从Map
对象写入文件.这是我的尝试.
I want to write to a file from a Map
object. Here is my attempt.
try {
stuMap.put(student.getId(), student);
Path file = Paths.get("student.txt"); // to create the file
Files.write(file, stuMap, Charset.forName("UTF-8")); // try to save in the file
/* fileReaderWriter.createFileIn_NIO(stuMap);*/
try {
fileReaderWriter.createFileIn_NIO(stuMap);
} catch (IOException ex) {
System.out.println("file not saved");
}
return true;
} catch (Exception ex) {
System.out.println("not stored in Map");
return false;
}
我如何进行这项工作?
推荐答案
解决此问题的简单方法是使用Gson库:
A simple variant to solve the problem is to use Gson library:
String str = new Gson().toJson(yourMap);
File file = new File(fileName);
try(FileOutputStream stream = new FileOutputStream(file)) {
file.createNewFile();
stream.write(str.getBytes());
}catch (IOException e){
System.out.println("can't write to file");
}
这篇关于如何将Map对象写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文