将传入的json串生成文件,文件地址作为参数传入C#后端接口生成shp文件,最后将文件打包并把压缩文件地址发给前端

import com.alibaba.fastjson.JSONObject;
import com.riskMonitor.service.acs4sql.IofJsonService;
import com.riskMonitor.utils.ConfigUtil;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import java.io.File;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service("ofJsonService")
public class OfJsonServiceImpl implements IofJsonService {
    private static Logger log = Logger.getLogger("OfJsonServiceImpl-->返回json文件或者shp文件路径");

    /*
    根据jsonStr生成json文件,并返回json文件地址
     */
    public JSONObject strToJson(String jsonStr) {
        JSONObject jo = new JSONObject();

        String json2ShpPath = ConfigUtil.getConfigPropertiesValue("Json2ShpPath");

        String s = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String jsonPath = json2ShpPath + File.separator + s + File.separator + "json" + File.separator + s + ".json";
        String shpPath = json2ShpPath + File.separator + s + File.separator + "shp" + File.separator + s + ".shp";

        // 格式化json字符串
        jsonStr = formatJson(jsonStr);

        // 保证创建一个新文件
        File file = new File(jsonPath);
        if (!file.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            file.getParentFile().mkdirs();
        }
//        if (file.exists()) { // 如果已存在,删除旧文件
//            file.delete();
//        }
        File shpFile = new File(shpPath);
        if (!shpFile.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            shpFile.getParentFile().mkdirs();
        }

        // 将格式化后的字符串写入文件
        Writer write = null;
        try {

            if(shpFile.createNewFile()){
                System.out.println("shp文件创建成功");

            }
            write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(jsonStr);
            write.flush();
            write.close();

            boolean result = true;
            List<String> commands = new ArrayList<>();
            commands.add("cmd.exe");
            commands.add("/c");
            commands.add  ("JsonToShp.exe");

            // 传入参数
            commands.add(jsonPath);// json文件绝对路径
            commands.add(shpPath);// shp文件绝对路径
            ProcessBuilder pb = new ProcessBuilder(commands);
            pb.directory(new File(json2ShpPath));// 设置工作目录
            Process p = pb.start();

            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in, "GBK"));
            String lineStr;
            StringBuffer outputInfo = new StringBuffer();
            while ((lineStr = inBr.readLine()) != null) {
                // 获得命令执行后在控制台的输出信息
                outputInfo.append(lineStr);
            }
            System.out.println("控制台打印消息:" + outputInfo);
            // 检查命令是否执行失败。

            if (p.waitFor() != 0) {
                // p.exitValue()==0表示正常结束,1:非正常结束
                if (p.exitValue() == 1) {
                    System.err.println("命令执行失败!");
                    result = false;
                }
            } else {
                // 执行成功之后
                System.out.println("执行成功");
            }

            inBr.close();
            in.close();
            p.destroy();//result=true;
            if (result) {
                // 成功之后
                jo.put("status", 1);// 1-成功
                jo.put("msg", "执行成功");

                String zipFile = getZipPath(s);
                if(!"".equals(zipFile)) {
                    jo.put("zipFile", zipFile);
                }
            } else {
                jo.put("status", 0);
                jo.put("msg", "执行失败");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            jo.put("status", 0);// 0-失败
            jo.put("msg", e.getMessage());// msg-失败信息
        }

      return jo;
    }

    /**
     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out           压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[(int) srcFile.length()];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getZipPath(String s) {
        //shpPath = "F:\\json\\data";
        String shpPath = ConfigUtil.getConfigPropertiesValue("Json2ShpPath") + File.separator + s + File.separator + "shp";

        List<File> versionZip = new ArrayList<>();
        File f = new File(shpPath);
        if (!f.exists()) {
            log.info(shpPath + " not exists");//不存在就输出
            return null;
        }

        File fa[] = f.listFiles();//用数组接收
        for (int i = 0; i < fa.length; i++) {//循环遍历
            File fs = fa[i];//获取数组中的第i个
            if (!fs.isDirectory() && fs.getName() != null) {
                versionZip.add(new File(shpPath + File.separator + fs.getName()));
            }
        }

        //压缩文件地址以及文件名
        String fileZip = ConfigUtil.getConfigPropertiesValue("Shp2Zip") + File.separator + s + ".zip";
        File zipFile = new File(fileZip);
        if (!zipFile.getParentFile().exists()) { // 如果父目录不存在,创建父目录
            zipFile.getParentFile().mkdirs();
        }

        OutputStream os=null;
        try {
            if(zipFile.createNewFile()){
                System.out.println("zip文件创建成功");

            }

            os=new FileOutputStream(zipFile);
            //调用压缩方法
            toZip(versionZip,os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭流
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(fileZip.indexOf("webapps")>0){
            return fileZip.substring(fileZip.indexOf("webapps")+8, fileZip.length());
        }
        return fileZip;

    }

    /**
     * 返回格式化JSON字符串。
     *
     * @param json 未格式化的JSON字符串。
     * @return 格式化的JSON字符串。
     */
    public String formatJson(String json) {
        StringBuffer result = new StringBuffer();

        int length = json.length();
        int number = 0;
        char key = 0;

        // 遍历输入字符串。
        for (int i = 0; i < length; i++) {
            // 1、获取当前字符。
            key = json.charAt(i);

            // 2、如果当前字符是前方括号、前花括号做如下处理:
            if ((key == '[') || (key == '{')) {
                // (1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
                if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
                    result.append('\n');
                    result.append(indent(number));
                }

                // (2)打印:当前字符。
                result.append(key);

                // (3)前方括号、前花括号,的后面必须换行。打印:换行。
                result.append('\n');

                // (4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
                number++;
                result.append(indent(number));

                // (5)进行下一次循环。
                continue;
            }

            // 3、如果当前字符是后方括号、后花括号做如下处理:
            if ((key == ']') || (key == '}')) {
                // (1)后方括号、后花括号,的前面必须换行。打印:换行。
                result.append('\n');

                // (2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
                number--;
                result.append(indent(number));

                // (3)打印:当前字符。
                result.append(key);

                // (4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
                if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
                    result.append('\n');
                }

                // (5)继续下一次循环。
                continue;
            }

            // 4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
            if ((key == ',')) {
                result.append(key);
                result.append('\n');
                result.append(indent(number));
                continue;
            }

            // 5、打印:当前字符。
            result.append(key);
        }

        return result.toString();
    }


    /**
     * 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。
     *
     * @param number 缩进次数。
     * @return 指定缩进次数的字符串。
     */
    private static String indent(int number) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < number; i++) {
            result.append("   ");//单位缩进字符串
        }
        return result.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值