【问题标题】:How to write a Map object to a file如何将 Map 对象写入文件
【发布时间】:2018-10-10 11:26:31
【问题描述】:

我想从 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;
}

我该如何进行这项工作?

【问题讨论】:

  • 如果您的 Student 类具有正确的 toString 方法,您可以毫无问题地写入文件。这段代码不好。打印堆栈跟踪或传递异常;不要向 System.out 写入消息。这比堆栈跟踪信息少。返回 true 或 false 并不能帮助用户处理问题。
  • 有六种不同的方法可以将对象图放到磁盘上。看序列化。查看xml格式。看json格式。等等。这个问题太宽泛了,我们无法回答。
  • 文件应该是人类可读的吗?你的地图可以序列化吗?
  • 应该可以读取文件并取回相同的对象吗?是否可以用其他程序语言读取文件?问题中没有提到这些事情的事实导致它过于宽泛。
  • 简单:您首先必须明确您的要求。您可以将各种内容写入文件。不管你做什么都是好的。如果您想阅读那里写的内容,它只会变得棘手。所以这是你必须首先澄清的事情!

标签: java nio


【解决方案1】:

您可以使用Jackson 之类的工具将java 映射写为json 并将其作为映射读入。正如其他人所提到的,这只是一种可能的方式。

完整的读/写示例

@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"
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        解决问题的一个简单变体是使用 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");
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-20
          • 2011-09-25
          • 2011-12-11
          • 2021-05-20
          • 2020-06-28
          • 2015-05-15
          相关资源
          最近更新 更多