ftp 文件读取,文件移动

FTPClient ftp = null;
List etcOrderVos = new ArrayList<>();
try {
    ftp = getFtpClient();
    boolean changeWorkingDirectoryFlag = ftp.changeWorkingDirectory("/");
    logger.info("转换路径是否成功={}", changeWorkingDirectoryFlag);
    // 获得指定目录下所有文件名
    FTPFile[] ftpFiles = ftp.listFiles("/");
    for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
        operateFile(ftp, ftpFiles[i], etcOrderVos);
    }
    ftp.logout();
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (ftp.isConnected()) {
        try {
            ftp.disconnect();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

 

/**
 * 处理文件数据
 *
 * @param ftp
 * @param ftpFile
 * @param etcOrderVos
 * @throws IOException
 */
private List operateFile(FTPClient ftp, FTPFile ftpFile, List etcOrderVos) throws IOException {
    FTPFile file = ftpFile;
    if (!file.isFile()) {
        return etcOrderVos;
    }
    InputStream ins = null;
    BufferedReader reader = null;
    try {
        // 从服务器上读取指定的文件
        ins = ftp.retrieveFileStream(file.getName());
        reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
        String line;
        int a = 0;
        while ((line = reader.readLine()) != null) {
            logger.info("line=" + line);
            if (a >= 1) {
                String[] str = line.split("\\|!");
                if ("1".equals(str[0])) {
                    String etcApplyNo = str[1];
                    String status = str[3];
                    EtcOrderVo etcOrderVo = new EtcOrderVo();
                    etcOrderVo.setEtcApplyNo(etcApplyNo);
                    etcOrderVo.setStatus(Integer.valueOf(status) == 0 ? 2 : 3);//2通过,3不通过
                    etcOrderVos.add(etcOrderVo);
                    logger.info("etc单号={}", etcApplyNo);
                    logger.info("etc该单号的状态={}", status);
                }
            }
            a++;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (ins != null) {
            ins.close();
            ftp.completePendingCommand();
        }
    }
    logger.info("是否转移成功" + ftp.rename(file.getName(), "/done/" + file.getName()));
    return etcOrderVos;
}

/**
 * 获取ftp连接
 * @return
 * @throws IOException
 */
private FTPClient getFtpClient() throws IOException {
    FTPClient ftp = new FTPClient();
    ftp.connect(ftpId);
    ftp.login(ftpUserName, ftpPassword);
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
    }
    ftp.enterLocalPassiveMode();
    //设置传输方式为流方式
    ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
    return ftp;
}

你可能感兴趣的:(ftp 文件读取,文件移动)