java 解析文件之后将源文件复制到bak文件下,并且保证源文件的目录,如果源文件下没有文件了,删除空目录

package com.comtop.sdap.file.scada.gz06.qtz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.comtop.sdap.common.enums.EFileNodeTypeEnums;
import com.comtop.sdap.common.utils.CommonUtils;
import com.comtop.sdap.file.scada.gz06.dao.GzXMLAnalysisDao;
import com.comtop.sdap.file.scada.gz06.model.AnalysisEfileLogVO;
import com.comtop.sdap.file.scada.gz06.model.DtDataVO;
import com.comtop.sdap.file.scada.gz06.model.FilesParamVO;
import com.comtop.sdap.file.scada.gz06.utils.SftpUtils;
import com.comtop.sdap.file.scada.gz06.utils.TransforWindingUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
/**
 * 贵州 -中调 - efile解析
 * @author wangchao5
 *
 */
@Service
public class GzZDXMLAnalysisService {

    @Resource
    GzXMLAnalysisDao analysisDao;

    @Resource
    private TransforWindingUtils transforWindingUtils;

    //e文件所在主目录
    private static String eFileDir;
    //备份E文件所在主目录
    private static String eBakFileDir;


    /**
     * 日志
     **/
    private static final Logger LOGGER = LoggerFactory.getLogger(GzZDXMLAnalysisService.class);
    
        
    /**
     * 中调数据解析(针对贵州的中调e文件)
     */
    public void dispatchGzDtData() {
        eFileDir = CommonUtils.getPropertiesKey("eFileDir", "properties/param.properties").trim();
        eBakFileDir = CommonUtils.getPropertiesKey("eBakFileDir", "properties/param.properties").trim();
        String bureauCode = CommonUtils.getPropertiesKey("bureauCode", "properties/param.properties").trim();
        String delBackupFile = CommonUtils.getPropertiesKey("delBackupFile", "properties/param.properties").trim();
        if(StringUtils.isNotBlank(eFileDir)&&StringUtils.isNotBlank(eBakFileDir)){
            File efile = new File(eFileDir);
            File eBakFile = new File(eBakFileDir);
            if(!efile.exists()){
                efile.mkdir();
                LOGGER.info("创建e文件目录成功过");
            }
            if(!eBakFile.exists()){
                eBakFile.mkdir();
                LOGGER.info("创建e文件备份目录成功");
            }
            LOGGER.info("中调数据文件目录:"+eFileDir);
            LOGGER.info("中调数据文件备份目录:"+eBakFileDir);
            /*LOGGER.info("--------------从SFTP服务上开始下载文件------------------");
            this.getEfileFromSftp(eFileDir);
            LOGGER.info("--------------从SFTP服务上结束下载文件------------------");*/
            recursiveFiles(new FilesParamVO(eFileDir,bureauCode,eBakFileDir,delBackupFile));           
        }else{
            LOGGER.info("文件目录未设置");
        }
    }

    /**
     * 中调数据文件下载
     */
    public void downLoadZDEile() {
        //sftp相关信息
        String sftpServerIp = CommonUtils.getPropertiesKey("sftpServerIp", "properties/param.properties").trim();
        String sftpServerPort = CommonUtils.getPropertiesKey("sftpServerPort", "properties/param.properties").trim();
        String sftpServerUser = CommonUtils.getPropertiesKey("sftpServerUser", "properties/param.properties").trim();
        String sftpServerPassword = CommonUtils.getPropertiesKey("sftpServerPassword", "properties/param.properties").trim();
        String targetSftpPath = CommonUtils.getPropertiesKey("targetSftpPath", "properties/param.properties").trim();
        String objectiveSftpPath = CommonUtils.getPropertiesKey("objectiveSftpPath", "properties/param.properties").trim();
        
        if(StringUtils.isNotBlank(sftpServerIp)&&StringUtils.isNotBlank(sftpServerPort) &&
                StringUtils.isNotBlank(sftpServerUser) && StringUtils.isNotBlank(sftpServerPassword)){
            try {
                int port = Integer.parseInt(sftpServerPort);
                SftpUtils.init(sftpServerIp, port, sftpServerUser, sftpServerPassword);
                List<String> lsFiles = this.download(targetSftpPath, objectiveSftpPath, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            LOGGER.info("文件目录未设置");
        }
    }
    
    /**
     * 文件下载
     *
     * @param remoteDirOrRemoteFile
     *             要下载的sftp上的文件 或 sftp上的文件夹 【绝对路径】
     *
     * @param localDir
     *             用于存放下载的文件的本地文件夹 【绝对路径】
     *             注:可以不存在,会自动创建
     *             注:可以不存在,会自动创建
     *
     * @param recursiveDownload
     *             当remoteDirOrRemoteFile指向文件夹时,此参数生效;
     *             为false时,
     *                  只下载remoteDirOrRemoteFile文件夹下的所有文件,remoteDirOrRemoteFile下的所
     *                  有文件夹(及里面的内容)将会被忽略
     *              为true时,
     *                      下载remoteDirOrRemoteFile文件夹下的所有文件、文件夹(及里面的内容)
     *
     * @return 下载到本地的文件的 绝对路径名  集合   如: /var/data/down/meinv.png
     * @throws SftpException 当未初始化就调用此方法是,会出现异常;当sftp下载出错时会抛出SftpException
     * @date 2019/10/14 12:44
     */
    public  List<String> download(String remoteDirOrRemoteFile, String localDir, boolean recursiveDownload)
            throws SftpException {
        if (SftpUtils.channelSftp == null) {
            throw new SftpException(SftpUtils.DONOT_INIT_ERROR_CODE, SftpUtils.DONOT_INIT_ERROR_MSG);
        }
        // 保证 localDir 以 “/” 结尾
        localDir = SftpUtils.handllePath(localDir, false, true);
        // 确保本地文件夹存在
        SftpUtils.pMkdirLocal(localDir);
        List<String> fileNameList = new ArrayList<>();
        String localAbsoluteFilename;
        String sftpAbsoluteFilename;
        try {
            if (SftpUtils.isDirectory(remoteDirOrRemoteFile)) {
                // 保证 remoteDirOrRemoteFile 以 “/” 开头,以 “/” 结尾
                remoteDirOrRemoteFile = SftpUtils.handllePath(remoteDirOrRemoteFile, true, true);
                Vector<?> vector = SftpUtils.channelSftp.ls(remoteDirOrRemoteFile);
                String fileName;
                // 列出文件名
                for (Object item : vector) {
                    ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) item;
                    fileName = entry.getFilename();
                    if(getEFileInfo(fileName) > 0){
                        continue;
                    }
                    //是否为无效文件名
                    if (SftpUtils.invalidFileName(fileName)) {
                        continue;
                    }
                    sftpAbsoluteFilename = remoteDirOrRemoteFile + fileName;
                    localAbsoluteFilename = localDir + fileName;
                    if (!SftpUtils.isDirectory(sftpAbsoluteFilename)) {
                        SftpUtils.channelSftp.get(sftpAbsoluteFilename, localAbsoluteFilename);
                        //下载完成之后,入库已下载信息
                        this.saveDownLoadEFile(fileName);
                        fileNameList.add(localAbsoluteFilename);
                        LOGGER.info("Downloaded file FROM 【{}】 TO 【{}】 ", sftpAbsoluteFilename, localAbsoluteFilename);
                        continue;
                    }
                    // 下载文件夹
                    if (recursiveDownload) {
                        SftpUtils.recursiveDownloadCloseFlag++;
                        download(sftpAbsoluteFilename, localAbsoluteFilename, true);
                        SftpUtils.recursiveDownloadCloseFlag--;
                    }
                }
            } else {
                // 保证 remoteDirOrRemoteFile 以 “/” 开头
                remoteDirOrRemoteFile = SftpUtils.handllePath(remoteDirOrRemoteFile, true, false);
                localAbsoluteFilename = localDir + SftpUtils.getFilenameFromPath(remoteDirOrRemoteFile);
                SftpUtils.channelSftp.get(remoteDirOrRemoteFile, localAbsoluteFilename);
                //下载完成之后,入库已下载信息
//                this.saveDownLoadEFile(fileName);
                fileNameList.add(localAbsoluteFilename);
                LOGGER.info("Downloaded file FROM 【{}】 TO 【{}】 ", remoteDirOrRemoteFile, localAbsoluteFilename);
            }
        } finally {
            if (SftpUtils.recursiveDownloadCloseFlag == 0) {
                SftpUtils.close();
            }
        }
        return fileNameList;
    }

    /**
     * 遍历文件/文件夹 - 函数
     * @param path
     */
    public void recursiveFiles (FilesParamVO objFilesParamVO){
        File readfiles = new File(objFilesParamVO.geteFileDir());
        File files[] = readfiles.listFiles();
        for (File readfile : files) {
            String strPath = readfile.getAbsolutePath().replace("\\", "/");
            if(objFilesParamVO.geteBakFileDir().indexOf(strPath)>=0){
                continue;
            }
            //备份文件夹如果不存在,创建
            File eBakFiles  = new File(objFilesParamVO.geteBakFileDir());
            if(!eBakFiles.exists()){
                eBakFiles.mkdir();
            }
            if (!readfile.isDirectory()) {
                LOGGER.info("读取文件开始-----"+readfile.getName());
                if(StringUtils.isNotEmpty(objFilesParamVO.getBureauCode()) && objFilesParamVO.getBureauCode().equals("0600")){
                    // LOGGER.info("读取贵州中调e文件开始");
                    this.readFileForGzDtData(readfile.getAbsolutePath(),readfile.getName());
                }
                LOGGER.info("读取文件结束-----"+readfile.getName());
                if(StringUtils.contains(objFilesParamVO.getDelBackupFile(), "true")){
                    readfile.delete();
                    LOGGER.info("删除文件" + readfile.getName()+"成功!");
                }else{
                    //获得备份目录
                    getEBakPath(objFilesParamVO,readfile,eFileDir,eBakFileDir);
                    if (readfile.renameTo(new File(objFilesParamVO.geteBakFileDir()))) {
                        LOGGER.info("文件移动成功!文件名:" + readfile.getName() + ";目标路径:" + objFilesParamVO.geteBakFileDir());
                        //如果此文件的上级目录对应的子目录为0,就删除此父目录
                        deleteParentFile(readfile);
                    } else {
                        LOGGER.info("文件移动失败!文件名:" + readfile.getName() + ";目标路径:" + objFilesParamVO.geteBakFileDir());
                        readfile.delete();
                        LOGGER.info("文件移动失败!删除文件,文件名:" + readfile.getName());
                    }
                }
            } else if (readfile.isDirectory()) {
                objFilesParamVO.seteFileDir(readfile.getAbsolutePath());
                //获得备份目录
                getEBakPath(objFilesParamVO,readfile,eFileDir,eBakFileDir);
                //如果是目录,继续解析
                recursiveFiles(objFilesParamVO);
            }
        }
        //如果此文件的上级目录对应的子目录为0,就删除此父目录
        deleteParentFile(readfiles);
    }

    /**
     * 删除此文件目录的上级目录(如果此文件上级目录没有子目录)
     * @param readfile
     */
    public void deleteParentFile(File readfile){
        if(readfile.getParentFile().listFiles().length == 0){
            readfile.getParentFile().delete();
            LOGGER.info("删除父目录成功:"+readfile.getParentFile().getName());
        }
    }

    /**
     * 获得备份目录
     * @param objFilesParamVO
     * @param file
     */
    public void  getEBakPath(FilesParamVO objFilesParamVO, File file,String eFileDir,String eBakFileDir){
        String strEfileBak = file.getAbsolutePath().replace("\\", "/").replace(eFileDir, eBakFileDir);
        objFilesParamVO.seteBakFileDir(strEfileBak);
    }

    /**
     * 读取文件(针对贵州的中调e文件)
     */
    private void readFileForGzDtData(String filePath,String fileName){
       //省略
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值