簡體   English   中英

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

[英]How to save a HashMap in a text file?

這是我的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<>();

您可以使用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":[]}]}

使用XMLEncoderXMLDecoder來執行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;
    }
}

如果您只是輸出文本,而不是任何二進制數據:

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

將您的String寫入其中,就像寫入任何輸出流一樣:

out.println(hashMap.toString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM