java 将字符输出到文件上丢失数据

这是我之前写的一个csv转json的代码

public class CsvAsJson {

    static class Data {
        String color;
        String uid;
        int row;
        int col;
        String time;

        public Data(String color, String uid, int row, int col, String time) {
            this.color = color;
            this.uid = uid;
            this.row = row;
            this.col = col;
            this.time = time;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public String getUid() {
            return uid;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        public int getRow() {
            return row;
        }

        public void setRow(int row) {
            this.row = row;
        }

        public int getCol() {
            return col;
        }

        public void setCol(int col) {
            this.col = col;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }
    }

    public static void main(String[] args) throws IOException {
        final LineNumberReader reader = new LineNumberReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("data.csv")));

        final List<Data> dataList = reader.lines().map(it -> {
            final String[] s = it.split(",");
            return new Data(s[4], s[5], Integer.parseInt(s[2]), Integer.parseInt(s[3]), s[6]);
        }).collect(Collectors.toList());
        com.google.gson.Gson gson = new Gson();
        // 这个就会导致丢失后半部分
        gson.toJson(dataList, new FileWriter("./target.json"));
        

}

当我用 gson.toJson(dataList, new FileWriter("./target.json"));
dataList 有3万多条数据, 但将dataList 输出到target.json后 并没有完整的输出,丢失了一部分

阅读 1.8k
1 个回答

FileWriter单独做一个变量拿出来
用完了之后 flush() 一下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题