WebService傳遞文件夾實戰---客戶端

客戶端需求是能定時請求文件,操作越簡單越好,所以我沒有弄springboot,寫成jar包,然後轉成exe點擊即用,項目結構如下:
在這裏插入圖片描述

1.文件的解壓與複製

import com.gwhn.service.ZipService;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Created by DLuser on 2019/11/7.
 */
public class ZipServiceImpl implements ZipService{
    private static final int BUFFER_SIZE = 2 * 1024;
/**
     * zip解壓
     * @param srcFile        zip源文件
     * @param destDirPath     解壓後的目標文件夾
     * @throws RuntimeException 解壓失敗會拋出運行時異常
     */
    @Override
    public void ZipToFile(File srcFile, String destDirPath) {
        long start = System.currentTimeMillis();
        if (!srcFile.exists()) { // 判斷源文件是否存在
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }
        // 開始解壓
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(srcFile);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
//                System.out.println("解壓" + entry.getName());
                if (entry.isDirectory()) { // 如果是文件夾,就創建個文件夾
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();
                } else {
                    File targetFile = new File(destDirPath + "/" + entry.getName());// 如果是文件,就先創建一個文件,然後用io流把內容copy過去
                    if(!targetFile.getParentFile().exists()){ // 保證這個文件的父文件夾必須要存在
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 將壓縮文件內容寫入到這個文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[BUFFER_SIZE];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.close();// 關流順序,先打開的後關閉
                    is.close();
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("解壓完成,耗時:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);
        } finally {
            if(zipFile != null){
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


/**
     * 複製文件
     * @param fromFile
     * @param toFile
     * <br/>
     * 2016年12月19日  下午3:31:50
     * @throws IOException
     */
    @Override
    public void copyFile(File fromFile, File toFile) throws Exception {
//        System.out.println("將文件"+fromFile.getPath()+"中零散數據複製到"+toFile.getPath());
        FileInputStream ins = new FileInputStream(fromFile);
        FileOutputStream out = new FileOutputStream(toFile);
        byte[] b = new byte[1024];
        int n=0;
        while((n=ins.read(b))!=-1){
            out.write(b, 0, n);
        }
        ins.close();
        out.close();
    }

2.路徑獲取

public class ReadConfig {
    /**
     * 讀取配置文件所有字符
     */
    public String readConfig() throws IOException, Exception {
        BufferedReader bufferedReader = null;
        File file = new File("C:\\Program Files\\config.txt");
        FileReader fileReader = new FileReader(file);//得到配置文件
        bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getPath()), "utf-8"));
        ;//用字符流讀取
        String word = "";
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {    //●判斷最後一行不存在,爲空
            word = word + str;
        }
        bufferedReader.close();//關閉字符流
        fileReader.close();
        return word;
    }

    /**
     * 獲取當天文件路徑
     * */
    public String getMicapsDataPath() throws Exception{
        String configTxt = readConfig();
        return configTxt.substring(configTxt.indexOf("每天數據放置路徑:")+9,configTxt.indexOf("日誌存放路徑"));
    }

    /**
     * 獲取日誌文件夾路徑
     * */
    public String getLogPath() throws Exception{
        String configTxt = readConfig();
        return configTxt.substring(configTxt.indexOf("日誌存放路徑:")+7,configTxt.indexOf("當天文件傳輸參數"));
    }

    /**
     *獲取文件傳輸參數
     * */
    public int getFileInt()throws Exception{
        String configTxt = readConfig();
        return Integer.parseInt(configTxt.substring(configTxt.indexOf("當天文件傳輸參數:")+9,configTxt.indexOf("以上配置均可自行修改")));
    }

    /**
     * 獲取webservice服務接口地址
     * */
    public String getWebServiceUrl() throws Exception{
        String configTxt = readConfig();
        return configTxt.substring(configTxt.indexOf("接口地址:")+5,configTxt.indexOf("每天數據放置路徑:"));
    }
}

config.txt:

WebService服務器接口地址:http://xxx.xxx.xxx.xxx:8080/webservice/service/micapsdata?wsdl
每天數據放置路徑:D:\\ideaworkspace
日誌存放路徑:D:\\ideaworkspace\\gwhnWebServiceLog
當天文件傳輸參數:-1
以上配置均可自行修改
若有其他配置需求請聯繫xxxx;

本服務每4個小時發送一次請求,若某天數據因網絡或去他問題未完成傳輸,
如:
   2019年11月6日文件未能傳輸,在2019年11月9日將參數修改爲-4,重啓本服務,確認目標文件傳輸完畢再將參數改回來,不必再次重啓
若多天數據丟失,請每修改一次參數重啓本服務,最後一次不必重啓。
若有其他問題,請聯繫xxxx;

3.本地服務

public class FileServiceImpl implements FileService{
    private Map<String, MicapsData> micapsDataMap = new HashMap<String, MicapsData>();

    @Override
    public MicapsData getZipMicapsdata(String name,String date) {
        MicapsData micapsData= micapsDataMap.get(name);
        return micapsData;
    }


//將字符串轉換爲原文件
    @Override
    public void writeFile(String fileString,String fileName,String path) throws Exception{
        byte[] bytes = Base64.decode(fileString);
        FileOutputStream out = new FileOutputStream(path+"\\"+fileName);// 寫入新文件
        out.write(bytes);
        out.flush();
        out.close();
    }

    /**
     * 生成文件夾字符集合
     */
    public List<String> getFilNameStringList() {
        List<String> pathList = new ArrayList<String>();
        pathList.add("10FG6");
        pathList.add("WIND_10M");
        pathList.add("WIND10M");
        pathList.add("gz");
        return pathList;
    }

    // 刪除文件夾
    public void deleteDirectory(File file) {
        if (file.isFile()) {// 表示該文件不是文件夾
            file.delete();
        } else {
            String[] childFilePaths = file.list();// 首先得到當前的路徑
            for (String childFilePath : childFilePaths) {
                File childFile = new File(file.getAbsolutePath() + "/" + childFilePath);
                deleteDirectory(childFile);
            }
            file.delete();
        }
    }

}

日期工具類見服務端,日誌工具如下:

public class LogUtil {

    /**
     * 獲取日誌文件
     */
    public File getLogFile() throws Exception {
        ReadConfig readConfig = new ReadConfig();
        File file = new File(readConfig.getLogPath()+".txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        return file;
    }

    /**
     * 獲取日誌文件所有字符
     */
    public String getLogString() throws Exception {
        File file = getLogFile();
        BufferedReader bufferedReader = null;
        FileReader fileReader = new FileReader(file);//得到配置文件
        bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getPath()), "utf-8"));
        ;//用字符流讀取
        String word = "";
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {    //●判斷最後一行不存在,爲空
            word = word + str;
        }
        bufferedReader.close();//關閉字符流
        fileReader.close();
        return word;
    }

    /**
     * 獲取日誌文件suo'you'所有字符
     */
    public void writeLog(String content) throws Exception {
        FileOutputStream fileOutputStream = null;
        ReadConfig readConfig = new ReadConfig();
        File file = getLogFile();
        String oldContent = getLogString();
        fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write((oldContent+"\t\t"+content).getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

自定義異常:

public class MyException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    /**
     * 錯誤編碼
     */
    private String errorCode;

    /**
     * 消息是否爲屬性文件中的Key
     */
    private boolean propertiesKey = true;

    /**
     * 構造一個基本異常.
     *
     * @param message 信息描述
     */
    public MyException(String message) {
        super(message);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message   信息描述
     */
    public MyException(String errorCode, String message) {
        this(errorCode, message, true);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message   信息描述
     */
    public MyException(String errorCode, String message, Throwable cause) {
        this(errorCode, message, cause, true);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode     錯誤編碼
     * @param message       信息描述
     * @param propertiesKey 消息是否爲屬性文件中的Key
     */
    public MyException(String errorCode, String message, boolean propertiesKey) {
        super(message);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message   信息描述
     */
    public MyException(String errorCode, String message, Throwable cause, boolean propertiesKey) {
        super(message, cause);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 構造一個基本異常.`在這裏插入代碼片`
     *
     * @param message 信息描述
     * @param cause   根異常類(可以存入任何異常)
     */
    public MyException(String message, Throwable cause) {
        super(message, cause);
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public boolean isPropertiesKey() {
        return propertiesKey;
    }

    public void setPropertiesKey(boolean propertiesKey) {
        this.propertiesKey = propertiesKey;
    }


}

最後時重點,客戶端的定時執行過程:

package com.gwhn;

import com.gwhn.entity.MicapsData;
import com.gwhn.service.FileService;
import com.gwhn.service.ZipService;
import com.gwhn.service.impl.FileServiceImpl;
import com.gwhn.service.impl.ZipServiceImpl;
import com.gwhn.util.DateUtil;
import com.gwhn.util.LogUtil;
import com.gwhn.util.MyException;
import com.gwhn.util.ReadConfig;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by DLuser on 2019/11/7.
 */
public class WebServiceClient {
    //通過接口協議獲取數據類型,設置鏈接超時和響應時間
    public  static void main(String[] args){

        //下面是循環執行內容
        Runnable runnable = new Runnable() {
            public void run() {
                System.out.println("WebService服務啓動 !!");
                // task to run goes here
                try {
                    ReadConfig readConfig = new ReadConfig();
                    JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
                    jaxWsProxyFactoryBean.setAddress(readConfig.getWebServiceUrl());//服務接口鏈接
                    jaxWsProxyFactoryBean.setServiceClass(FileService.class);

                    FileService fileService = (FileService) jaxWsProxyFactoryBean.create(); // 創建客戶端對象
                    Client proxy = ClientProxy.getClient(fileService);
                    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
                    HTTPClientPolicy policy = new HTTPClientPolicy();
                    policy.setConnectionTimeout(10000000);
                    policy.setReceiveTimeout(1000000);
                    conduit.setClient(policy);

                    DateUtil dateUtil = new DateUtil();
                    ZipService zipService = new ZipServiceImpl();
                    String date = dateUtil.getDate(readConfig.getFileInt());
                    String path = readConfig.getMicapsDataPath();//每日文件夾放置路徑
                    File file = new File(path + "\\" + date);
                    if (!file.exists()) {//如果當天文件夾不存在,則新增該文件夾
                        file.mkdirs();
                    }
                    if (file.length() > 300 * 1024) {
                        throw new MyException("文件已存在,無需再傳");
                    }
                    File tempFile = new File(path + "\\gztemp");
                    if (!tempFile.exists()) {//如果當天文件夾不存在,則新增該文件夾
                        tempFile.mkdirs();
                    }
                    /**開始傳輸文件*/
                    FileService fileServicelocal = new FileServiceImpl();
                    List<String> list = fileServicelocal.getFilNameStringList();
                    for (int i = 0; i < list.size(); i++) {
                        File temp = new File(path + "\\" + date + "\\" + list.get(i));
                        if (!temp.exists()) {
                            temp.mkdirs();
                        }
                        System.out.println(date + list.get(i) + ".zip," + date);
                        MicapsData micapsData = fileService.getZipMicapsdata(date + list.get(i) + ".zip", date);
                        System.out.println("第" + (i + 1) + "個壓縮包" + date + list.get(i) + ".zip開始傳輸");
                        fileServicelocal.writeFile(micapsData.getEncodedFileString(), date + list.get(i) + ".zip", path + "\\gztemp");
                        System.out.print(date + list.get(i) + ".zip傳輸完畢");
                        System.out.print(date + list.get(i) + ".zip開始解壓");
                        File zipFile = new File(path + "\\gztemp\\" + date + list.get(i) + ".zip");
                        zipService.ZipToFile(zipFile, path + "\\" + date);
                        /**轉移零散文件到目標目錄下*/
                    }
                    System.out.println("解壓完畢,開始轉移");
                    File micapsFile = new File(path + "\\" + date + "\\" + date + "gz");
                    List<String> micapsFileList = new ArrayList<String>();
                    File[] fileList = micapsFile.listFiles();
                    for (int i = 0; i < fileList.length; i++) {
                        if (!fileList[i].isDirectory()) {
                            File srcfile = new File(fileList[i].getPath());
//                    File gzFile = new File("D:\\zhpfile\\ideaworkspace\\gz19102820\\");
                            File gzFile = new File(path + "\\" + date);
                            File tofile = new File(gzFile.getPath() + "\\" + srcfile.getName());
                            zipService.copyFile(srcfile, tofile);//文件移動完成
                        }
                    }

                    //移動完畢,開始刪除臨時緩存文件
                    System.out.print("移動完畢,開始刪除臨時緩存文件");
                    fileServicelocal.deleteDirectory(micapsFile);
                    fileServicelocal.deleteDirectory(tempFile);
                    File tpFile = new File(path + "\\" + date + "\\gz");
                    fileServicelocal.deleteDirectory(tpFile);
                    LogUtil logUtil = new LogUtil();
                    String newLog = dateUtil.getDate() + "成功獲取" + file.getPath();
                    logUtil.writeLog(newLog);
                    System.out.print("刪除完畢,本次行爲結束");
                    MicapsData micapsData = fileService.getZipMicapsdata("1", "1");
                } catch (Exception e) {
                    try {
                        LogUtil logUtil = new LogUtil();
                        DateUtil dateUtil = new DateUtil();
                        String newLog = dateUtil.getDate() + "本次獲取失敗";
                        logUtil.writeLog(newLog);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }
        };
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        service.scheduleAtFixedRate(runnable, 0, 14400, TimeUnit.SECONDS);//每4個小時傳一次請求

    }
}

調試完畢後打jar包,通過exe4j轉換爲exe程序,將config.txt放到C:\Program Files下,點擊即可運行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章