将文件夹里的所有文件转成JSON文件

avatar 2020年09月11日09:40:37 6 3651 views
博主分享免费Java教学视频,B站账号:Java刘哥

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>File2JSON</groupId>
    <artifactId>com.example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>
    </dependencies>
</project>

 

FileDTO

package com.example.model;

public class FileDTO {

    private String fileName;

    private String relativePath;

    private String absolutePath;
    /**
     * 0 文件夹,1文件
     */
    private Integer fileType;

    private String content;

    public FileDTO(String fileName, String relativePath, String absolutePath, Integer fileType, String content) {
        this.fileName = fileName;
        this.relativePath = relativePath;
        this.absolutePath = absolutePath;
        this.fileType = fileType;
        this.content = content;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getRelativePath() {
        return relativePath;
    }

    public void setRelativePath(String relativePath) {
        this.relativePath = relativePath;
    }

    public String getAbsolutePath() {
        return absolutePath;
    }

    public void setAbsolutePath(String absolutePath) {
        this.absolutePath = absolutePath;
    }

    public Integer getFileType() {
        return fileType;
    }

    public void setFileType(Integer fileType) {
        this.fileType = fileType;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

 

FileUtils

package com.example.utils;

import java.io.*;

public class FileUtils {

    /**
     * 从文件里读取内容
     *
     * @param filePath
     * @return
     */
    public static String readFromFile(String filePath) {
        // 使用ArrayList来存储每行读取到的字符串
        StringBuilder sb = new StringBuilder();
        try {
            FileReader fr = new FileReader(filePath);
            BufferedReader bf = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                sb.append(str + "\r\n");
            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    /**
     * 往文件中写入内容
     *
     * @param outputFilePath 输出文件路径
     * @param content
     */
    public static void writeToFile(String outputFilePath, String content)  {
        File file = new File(outputFilePath);
        File parent = new File(file.getParent());
        parent.mkdirs();
        try {
            FileWriter writer = new FileWriter(file);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

测试类 Main

package com.example;

import com.alibaba.fastjson.JSON;
import com.example.model.FileDTO;
import com.example.utils.FileUtils;

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

public class Main {
    public static final List<String> excludeFileNameList = Arrays.asList(new String[]{".idea", "target", "out"});


    public static void main(String[] args) throws IOException {

        String originPath = "D:\\Users\\zhangsan\\Desktop\\train\\java-basic";
        String targetPath = "D:\\Users\\zhangsan\\Desktop\\target.json";
        // 将文件夹转成JSON
        file2json(originPath, targetPath);

        // 将JSON格式的文件还原成文件夹
        // json2file("D:\\Users\\zhangsan\\Desktop\\target.json", "D:\\Users\\zhangsan\\Desktop\\tmp");
    }

    public static void file2json(String originPath, String targetPath) throws IOException {
        Set<File> fileSet = new HashSet<File>();
        getAllFileAndFolder(new File(originPath), fileSet);
        List<FileDTO> fileDTOList = new ArrayList<FileDTO>();
        // 获得文件路径
        for (File file : fileSet) {
            FileDTO fileDTO;
            if (file.isFile()) {
                fileDTO = new FileDTO(file.getName(), file.getPath().substring(originPath.length() + 1), file.getAbsolutePath(), 1, FileUtils.readFromFile(file.getPath()));
            } else {
                fileDTO = new FileDTO(file.getName(), file.getPath().substring(originPath.length() + 1), file.getAbsolutePath(), 0, "");
            }
            fileDTOList.add(fileDTO);
        }

        FileUtils.writeToFile(targetPath, JSON.toJSONString(fileDTOList));
    }


    public static void json2file(String originPath, String targetPath) throws IOException {
        String json = FileUtils.readFromFile(originPath);
        List<FileDTO> fileDTOList = JSON.parseArray(json, FileDTO.class);
        System.out.println(fileDTOList);
        for (FileDTO fileDTO : fileDTOList) {
            File file = new File(targetPath + File.separator + fileDTO.getRelativePath());
            if (fileDTO.getFileType() == 0) {
                file.mkdirs();
            } else {
                FileUtils.writeToFile(targetPath + File.separator + fileDTO.getRelativePath(), fileDTO.getContent());
            }
        }
    }

    private static void getAllFileAndFolder(File folder, Set<File> all) {
//        all.add(folder);
        if (folder.isFile()) {
            return;
        }
        for (File file : folder.listFiles()) {
            if (!excludeFileNameList.contains(file.getName()) && file.getName().indexOf(".iml") == -1) {
                all.add(file);
                if (file.isDirectory()) {
                    getAllFileAndFolder(file, all);
                }
            }
        }
    }
}

 

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0