如何将Map对象写入文件

时间:2018-10-10 11:26:32

标签: java nio

我想从Map对象写入文件。这是我的尝试。

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;
}

我如何进行这项工作?

4 个答案:

答案 0 :(得分:2)

您可以使用Jackson之类的工具将Java Maps作为json编写并作为map读入。正如其他人提到的那样,这只是一种可能的方式。

示例

@Test
public void loadMapFromFileAndSaveIt(){
    Map<Object, Object> map = loadMap("map.json");
    map.put("8", "8th");
    map.remove("7");
    save(map,"/path/to/map2.txt");
}

private Map<Object, Object> loadMap(String string) {
    ObjectMapper mapper = new ObjectMapper();
    try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("map.json")) {
        return mapper.readValue(in, HashMap.class);
    }catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private void save(Map<Object, Object> map,String path) {
    try (PrintWriter out = new PrintWriter(path)) {
        out.println(toString(map));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

public String toString(Object obj) {
    try (StringWriter w = new StringWriter();) {
        new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
        return w.toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

如果您的类路径中的文件map.json包含

{
 "1":"1th",
 "2":"2th",
 "3":"3th",
 "4":"4th",
 "5":"5th",
 "6":"6th",
 "7":"7th"
}

上面的代码将对其进行修改并将其写入包含以下内容的文件/path/to/map2.txt

{
  "1" : "1th",
  "2" : "2th",
  "3" : "3th",
  "4" : "4th",
  "5" : "5th",
  "6" : "6th",
  "8" : "8th"
}

答案 1 :(得分:1)

java中有一个用于保存对象状态并稍后将其取回的概念,称为“序列化”。
写对象

File fileToSaveObject=new File("path");
Object objectToSave=new Object();

FileOutputStream fileOut = new FileOutputStream(fileToSaveObject);
ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(objectToSave); // It will save 'objectToSave' in given file

out.close();
fileOut.close(); 

读取对象

File fileToReadObject=new File("path");
Object objectToRead;

FileInputStream fileIn = new FileInputStream(fileToReadObject);
ObjectInputStream in = new ObjectInputStream(fileIn);

objectToRead= (Object) in.readObject();  // It will return you the saved object

in.close();
fileIn.close();

答案 2 :(得分:0)

解决此问题的一个简单变体是使用Gson库:

    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");
    }

答案 3 :(得分:0)

只需使用org.apache.commons.io.FileUtils

import org.apache.commons.io.FileUtils;

yourMap.forEach((key, value) -> {
    FileUtils.writeStringToFile(
            outputFile, key + ", " + value + "\n", true);
});