WebService传递文件夹实战---客户端

客户端需求是能定时请求文件,操作越简单越好,所以我没有弄springboot,写成jar包,然后转成exe点击即用,项目结构如下:
WebService传递文件夹实战---客户端_第1张图片

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
     * 
* 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 micapsDataMap = new HashMap();

    @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 getFilNameStringList() {
        List pathList = new ArrayList();
        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 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 micapsFileList = new ArrayList();
                    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下,点击即可运行

你可能感兴趣的:(WebService)