如何在文本文件中保存HashMap?

时间:2016-09-12 08:19:39

标签: java

这是我显示的WordHashMap对象的类。我想将它保存在Java中的文本文件中。请指导我。

public class Word 
{
    private String path;
    private transient int frequency;
    private List<Integer> lindex=new ArrayList<Integer>();
}
HashMap<String,List<Word>> hashMap = new HashMap<>();

3 个答案:

答案 0 :(得分:0)

您可以使用Jackson XML执行此任务。

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

public class Main {
    private static class Word implements Serializable {
        public void setPath(String s) {
            this.path = s;
        }
        @JsonProperty
        private String path;
        @JsonProperty
        private transient int frequency;
        @JsonProperty
        private List<Integer> lindex = new ArrayList<Integer>();
    }

    public static void main(String[] args) throws JsonParseException, IOException {
        HashMap<String, List<Word>> hashMap = new HashMap<>();
        ArrayList a = new ArrayList<Word>();
        Word w1 = new Word();
        Word w2 = new Word();
        Word w3 = new Word();
        w1.setPath("dev");
        w2.setPath("media");
        w3.setPath("etc");
        a.add(w1);
        a.add(w2);
        a.add(w3);
        hashMap.put("key1", a);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(new File("data.json"), hashMap);
    }
}

输出文件data.json

{"key1":[{"path":"dev","lindex":[]},{"path":"media","lindex":[]},{"path":"etc","lindex":[]}]}

答案 1 :(得分:0)

使用执行bean序列化的XMLEncoderXMLDecoder可能最简单:

static void write(Map<?, ?> map,
                  Path path)
throws IOException {
    try (XMLEncoder encoder = new XMLEncoder(
        new BufferedOutputStream(
            Files.newOutputStream(path)))) {

        final Exception[] exception = { null };
        encoder.setExceptionListener(e -> exception[0] = e);
        encoder.writeObject(map);

        if (exception[0] != null) {
            throw new IOException(exception[0]);
        }
    }
}

static Map<?, ?> read(Path path)
throws IOException {
    try (XMLDecoder decoder = new XMLDecoder(
        new BufferedInputStream(
            Files.newInputStream(path)))) {

        final Exception[] exception = { null };
        decoder.setExceptionListener(e -> exception[0] = e);
        Map<?, ?> map = (Map<?, ?>) decoder.readObject();

        if (exception[0] != null) {
            throw new IOException(exception[0]);
        }

        return map;
    }
}

答案 2 :(得分:-1)

如果您只是输出文本,而不是任何二进制数据:

PrintWriter out = new PrintWriter("filename.txt");

将String写入其中,就像对任何输出流一样:

out.println(hashMap.toString());