package com.yqzx.common.util;
|
|
import cn.hutool.core.convert.Convert;
|
import cn.hutool.core.io.FileUtil;
|
import cn.hutool.extra.ftp.Ftp;
|
import cn.hutool.extra.ftp.FtpMode;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.net.ftp.FTP;
|
import org.springframework.core.io.DefaultResourceLoader;
|
import org.springframework.core.io.ResourceLoader;
|
|
import java.io.File;
|
import java.io.IOException;
|
import java.io.InputStream;
|
import java.util.Properties;
|
|
/**
|
* @author ChenLong
|
* @version 1.0
|
* @ClassName FtpUtil
|
* @date 2019/4/15 14:16
|
*/
|
@Slf4j
|
public class FtpUtil {
|
|
public static Properties getFtpProp() {
|
Properties props = new Properties();
|
InputStream in = null;
|
try {
|
ResourceLoader resourceLoader = new DefaultResourceLoader();
|
in = resourceLoader.getResource("ftp.properties").getInputStream();
|
props.load(in);
|
return props;
|
} catch (IOException e) {
|
log.error(e.getMessage());
|
return props;
|
} finally {
|
ResourceUtil.safeClose(in);
|
}
|
|
}
|
|
public static Ftp getFtp() {
|
|
Properties props = getFtpProp();
|
String url = props.getProperty("ftp.url");
|
int port = Convert.toInt(props.getProperty("ftp.port"));
|
String username = props.getProperty("ftp.username");
|
String mixpd = props.getProperty("ftp.mixpd");
|
|
Ftp ftp = new Ftp(url, port, username, mixpd);
|
ftp.setMode(FtpMode.Passive);
|
ftp.getClient().setActivePortRange(50000, 55000);
|
ftp.getClient().setRemoteVerificationEnabled(false);
|
try {
|
ftp.getClient().setFileType(FTP.BINARY_FILE_TYPE);
|
} catch (IOException e) {
|
log.error(e.getMessage());
|
}
|
return ftp;
|
}
|
|
public static void upload(Ftp ftp, String sourceFilePath,String targetFilePath) {
|
String FileName = targetFilePath.substring(targetFilePath.lastIndexOf("/") + 1);
|
String targetPath = targetFilePath.substring(0, targetFilePath.lastIndexOf("/"));
|
ftp.upload(targetPath, FileName, new File(sourceFilePath));
|
}
|
|
public static void upload(Ftp ftp, String FileName,InputStream inputStream,String targetPath) {
|
ftp.upload(targetPath,FileName,inputStream);
|
}
|
|
public static void download(Ftp ftp, String sourceFilePath,String targetFilePath) {
|
String sourceName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1);
|
String sourcePath = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/"));
|
ftp.download(sourcePath, sourceName, FileUtil.file(targetFilePath));
|
}
|
|
public static void close(Ftp ftp) {
|
if (ftp != null) {
|
try {
|
ftp.close();
|
} catch (IOException e) {
|
log.error(e.getMessage());
|
}
|
}
|
}
|
}
|