1. 程式人生 > 其它 >java- 使用Jaxb將xml轉換為javabean與檔案移動並生成壓縮檔案

java- 使用Jaxb將xml轉換為javabean與檔案移動並生成壓縮檔案


typora-root-url: C:\Users\Administrator\Desktop\ty\img

java xml轉換為javabean 與檔案生成

1.準備xml對應的javabean(可根據xsd生成詳情見https://blog.csdn.net/weixin_48250973/article/details/113525514)

2.準備一個xml測試檔案

<?xml version="1.0" encoding="utf-8"?>
<Package>
    <EnvelopInfo>

    </EnvelopInfo
>
<DataInfo> <BussinessData> <EMS211> <EmsPutrecDt> <emsNo>111589</emsNo> <chgTmsCnt>18465323</chgTmsCnt> <gdsSeqno>2332145</gdsSeqno> <
mtpckEndprdTypecd
>
test</mtpckEndprdTypecd> <gdsMtno>test</gdsMtno> <gdecd>test</gdecd> <gdsNm>test</gdsNm> <endprdGdsSpcfModelDesc>test</endprdGdsSpcfModelDesc> <
dclUnitcd
>
test</dclUnitcd> <lawfUnitcd>test</lawfUnitcd> </EmsPutrecDt> <EmsPutrecUcnsDt></EmsPutrecUcnsDt> </EMS211> </BussinessData> </DataInfo> </Package>

3.將xml檔案放入一個資料夾(本人使用的為appData資料夾)

在這裡插入圖片描述

4.讀取測試xml所在資料夾

​ 使用泛型因為有多種型別的xml檔案 type為報文型別

   public static <T> T xmlFileListener(String type,Class<T> t){
        String path=System.getenv("APPDATA")+"\\xml_message\\"+"\\message_reception\\";
        File listenerFile = new File(path);
        listener(listenerFile,type,t);
        return null;
    }

​ 監聽xml 使用遞迴找到檔案xml 完成生成bean時將對應的資料夾 並且移動到另一個資料夾中 防止反覆掃描

   private static <T> T listener(File file,String type, Class<T> t){
        Date date1 = new Date();
        String dataForm = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        for (File listFile : file.listFiles()) {
            if(listFile.isDirectory()){
                listener(file,type,t);
            }
            else{
                // 監聽到xml報文檔案 讀取報文檔案
                String s = doListener(listFile);
                // 將string轉換為對應業務的xml物件 使用泛型使用時確定轉換的bean
                T t1= JaxbUtils.converyToJavaBean(s, t);
                // 根據業務型別 進行業務處理
                Boolean result = true;
                // todo

                // 如果操作正確 將當前檔案移動到成功資料夾下
                if(result){
                    String path=System.getenv("APPDATA")+"\\xml_message\\"+"\\message_reception_his\\"+dataForm;
                    String xmString= JaxbUtils.convertToXml(t1);
                    System.out.println(xmString);
                    removefile(xmString, type,path);
                    //刪除原有檔案
                    listFile.delete();
                }
                // 如果操作錯誤 將當前檔案移動到錯誤資料夾下
                else{
                    String path=System.getenv("APPDATA")+"\\xml_message\\"+"\\message_reception_error\\"+dataForm;
                    String xmString= JaxbUtils.convertToXml(t1);
                    removefile(xmString, type,path);
                    //刪除原有檔案
                    listFile.delete();
                }


            }
        }
        return null;
    }

/**讀取xml檔案轉換為string*/  
private static String doListener(File file) {

        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String str;
            while ((str = reader.readLine()) != null)
            {
                builder.append(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                assert reader != null;
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return builder.toString();

    }

​ 移動檔案的方法(移動後要刪除原有檔案(移動後文件為壓縮檔案)

/**
     * 移動檔案
     * @param xmString
     * @param type
     * @param path
     */
    private static void removefile(String xmString,String type,String path) {
        Date date1 = new Date();
        // 如果不存在,建立資料夾
        File f = new File(path);
        if(!f.exists()){
            f.mkdirs();
        }
        String filePath = f.getAbsolutePath();
        System.out.println(filePath);
        // 建立檔名
        String dataForm1 = new SimpleDateFormat("yyyyMMddHHmmss").format(date1);
        String zipFileName = "\\"+dataForm1+type+".zip";
        String xmlFileName = dataForm1+type;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        DataOutputStream dataOs;
        try {
            ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(path+zipFileName));
            ZipEntry entry = new ZipEntry(xmlFileName+".xml");
            zip.putNextEntry(entry);
            dataOs = new DataOutputStream(zip);
            dataOs.write(xmString.getBytes());
            dataOs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
          dataOs.write(xmString.getBytes());
            dataOs.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }