Java 如何在文本文件中保存哈希映射?

Java 如何在文本文件中保存哈希映射?,java,Java,下面是我的Word和HashMap对象类。我想用Java把它保存在文本文件中。请引导我 public class Word { private String path; private transient int frequency; private List<Integer> lindex=new ArrayList<Integer>(); } 公共类单词 { 私有字符串路径; 专用瞬态int频率; private List lindex=n

下面是我的
Word
HashMap
对象类。我想用Java把它保存在文本文件中。请引导我

public class Word 
{
    private String path;
    private transient int frequency;
    private List<Integer> lindex=new ArrayList<Integer>();
}
公共类单词
{
私有字符串路径;
专用瞬态int频率;
private List lindex=new ArrayList();
}
HashMap HashMap=newhashmap();

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

PrintWriter out = new PrintWriter("filename.txt");
将字符串写入其中,就像写入任何输出流一样:

out.println(hashMap.toString());

您可以将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);
    }
}

它可能最容易使用,并执行bean序列化:

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;
    }
}
静态无效写入(映射,
路径(路径)
抛出IOException{
尝试(XMLEncoder编码器=新的XMLEncoder(
新的缓冲输出流(
文件。newOutputStream(路径))){
最终异常[]异常={null};
编码器.setExceptionListener(e->exception[0]=e);
编码器。写入对象(map);
如果(异常[0]!=null){
抛出新IOException(异常[0]);
}
}
}
静态映射读取(路径)
抛出IOException{
尝试(XMLDecoder decoder=新的XMLDecoder)(
新的BufferedInputStream(
文件。newInputStream(路径))){
最终异常[]异常={null};
解码器.setExceptionListener(e->exception[0]=e);
Map Map=(Map)解码器.readObject();
如果(异常[0]!=null){
抛出新IOException(异常[0]);
}
返回图;
}
}

添加一个
toString
方法,将地图转换为可读格式。您可以使用JSON进行此操作。另存为什么?;)您需要有地图的数据表示。例如,您可以保存为json、xml、csv。。。选择要先保存的格式-然后保存;)这将写入HashMap数据,但是如何读回它呢?请记住,键和值本身可能包含
=
[
]
,以及
{"key1":[{"path":"dev","lindex":[]},{"path":"media","lindex":[]},{"path":"etc","lindex":[]}]}
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;
    }
}