ftp工具类

       文章主要介绍ftp工具类,主要包括FTPUtil工具类使用实例、FTP连接、FTP上传文件、下载文件等,具有一定的参考价值,需要的朋友可以参考一下。

public class FTPUtil {

private final Logger logger = LoggerFactory.getLogger(FTPUtil.class); 

private static String encoding = "UTF-8";

/**

* ftp客户端

*/

FTPClient ftpClient;

/**

* ftp服务器地址

*/

private String host;

/**

* ftp 端口号 默认21

*/

private int port = 21;

/**

* ftp服务器用户名

*/

private String username;

/**

* ftp服务器密码

*/

private String password;

/**

* ftp远程目录

*/

private String remoteDir;

/**

* 本地存储目录

*/

private String localDir;

/**

* 文件路径通配符 默认列出所有

*/

private String regEx = "*";

/**

* 指定要下载的文件名

*/

private String downloadFileName;

public FTPUtil setConfig(String host, String username, String password) {

this.host = host;

this.username = username;

this.password = password;

return this;

}

public FTPUtil setConfig(String host, int port, String username,String password) {

this.host = host;

this.port = port;

this.username = username;

this.password = password;

return this;

}

private void connectServer() throws Exception{

if(this.ftpClient == null) {

this.ftpClient = new FTPClient();

}

//设置超时时间

this.ftpClient.setConnectTimeout(30000);

try {

// 1、连接服务器

if(!this.ftpClient.isConnected()){

// 如果采用默认端口,可以使用client.connect(host)的方式直接连接FTP服务器

this.ftpClient.connect(this.host, this.port);

// 登录

this.ftpClient.login(this.username, this.password);

// 获取ftp登录应答码

int reply = this.ftpClient.getReplyCode();

// 验证是否登陆成功

if (!FTPReply.isPositiveCompletion(reply)) {

logger.info("未连接到FTP,用户名或密码错误。");

this.ftpClient.disconnect();

throw new RuntimeException("未连接到FTP,用户名或密码错误。");

} else {

logger.info("FTP连接成功。IP:"+host +"PORT:" +port);

}

// 2、设置连接属性

this.ftpClient.setControlEncoding(FTPUtil.encoding);

// 设置以二进制方式传输

this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 

this.ftpClient.enterLocalPassiveMode();

}

} catch (Exception e) {

try {

this.ftpClient.disconnect();

} catch (IOException e1) {

}

logger.error("连接FTP服务器出现异常,参数:ip="+this.host+",port="+this.port+",user="+this.username+",password="+this.password);

}

}

public List<String> fileReaderByRow(String remoteFileName)throws Exception{

if(remoteFileName == null || "".equals(remoteFileName.trim())) {

}else {

List<String> rowList = new ArrayList<String>();

InputStream input = null;

BufferedReader reader = null;

this.connectServer();

InputStream is = null;

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、设置文件名通配符

this.regEx = remoteFileName+"*";

// 3、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length == 0) {

logger.warn("文件数为0,没有可下载的文件!");

return null;

}else if(ftpFiles.length > 1) {

logger.warn("文件数为"+ftpFiles.length+"个,并不是唯一文件!");

return null;

}else {

logger.info("准备下载" + ftpFiles.length + "个文件");

// 4、获得文件流读取文件内容

FTPFile file = ftpFiles[0];

is = this.ftpClient.retrieveFileStream(file.getName());

if(is==null){

throw new RuntimeException("下载失败,检查文件是否存在");

}

//将流整体读取。

reader = new BufferedReader(new InputStreamReader(is,"utf-8"));

String str;

//判断是否是最后一行

while((str=reader.readLine())!=null){

// logger.debug("输出每一行内容:"+str);//输出每一行内容。

rowList.add(str);

}

}

} catch (IOException ex) {

logger.error("ftp文件行集记录读取出现异常,参数remoteFileName="+remoteFileName);

} finally {

try {

if (input != null) {

input.close();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(reader != null) {

reader.close();

}

}catch (Exception e) {

e.printStackTrace();

}

}

}

return rowList;

}

}

public void uploadRowValueList(String remoteFileName, List<String> rowValueList)throws Exception{

if(remoteFileName == null || "".equals(remoteFileName.trim())) {

}else if(rowValueList == null || rowValueList.size() == 0){

}else {

OutputStream os = null;

BufferedWriter bw = null;

try {

this.connectServer();

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 将远程文件加入输出流中

os = this.ftpClient.storeFileStream(remoteFileName);

if(os == null) {

throw new RuntimeException("上传失败,请检查是否有上传权限");

}

// 创建一个缓冲区

bw = new BufferedWriter(new OutputStreamWriter(os));

for (String rowValue : rowValueList) {

bw.write(rowValue+"\r\n");

}

bw.flush();

} catch (Exception ex) {

logger.error("ftp上传行值记录集出现异常,参数remoteFile="+remoteFileName+",rowValueList="+rowValueList);

} finally {

try {

if (os != null) {

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (bw != null) {

bw.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

public List<File> download()throws Exception{

List<File> files = null;

this.connectServer();

InputStream is = null;

File downloadFile = null;

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return null;

}

logger.info("准备下载" + ftpFiles.length + "个文件");

// 3、保存文件到本地

for (FTPFile file : ftpFiles) {

//如果有指定下载的文件

if(!StrUtil.isNullOrEmpty(this.downloadFileName) && !file.getName().equals(this.downloadFileName)){

continue;

}

if(files == null) files = new ArrayList<File>();

is = this.ftpClient.retrieveFileStream(file.getName());

if(is==null) {

throw new RuntimeException("下载失败,检查文件是否存在");

}

downloadFile = new File(this.localDir + file.getName());

FileOutputStream fos = FileUtils.openOutputStream(downloadFile);

IOUtils.copy(is, fos);

this.ftpClient.completePendingCommand();

IOUtils.closeQuietly(is);

IOUtils.closeQuietly(fos);

files.add(downloadFile);

}

logger.info("文件下载成功,下载文件路径:" + this.localDir);

} catch (IOException e) {

logger.error("ftp下载文件出现异常,参数remoteDir="+this.remoteDir+",localDir="+this.localDir+",regEx="+this.regEx+",downloadFileName="+this.downloadFileName);

}

return files;

}

public List<File> download(String remoteDir,String localDir)throws Exception{

this.remoteDir = remoteDir;

this.localDir = localDir;

return this.download();

}

public List<File> download(String remoteDir,String regEx,String localDir)throws Exception{

this.remoteDir = remoteDir;

this.localDir = localDir;

this.regEx = regEx;

return this.download();

}

public List<File> download(String downloadFileName)throws Exception{

this.downloadFileName = downloadFileName;

return this.download();

}

public void upload(List<File> files)throws Exception{

OutputStream os = null;

try {

// 2、取本地文件

if(files == null || files.size()==0) {

logger.warn("文件数为0,没有找到可上传的文件");

return;

}

logger.info("准备上传" + files.size() + "个文件");

// 3、上传到FTP服务器

for(File file : files){

this.connectServer();

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

os = this.ftpClient.storeFileStream(file.getName());

if(os== null) {

throw new RuntimeException("上传失败,请检查是否有上传权限");

}

IOUtils.copy(new FileInputStream(file), os);

IOUtils.closeQuietly(os);

}

logger.info("文件上传成功,上传文件路径:" + this.remoteDir);

} catch (IOException e) {

logger.error("ftp上传文件出现异常,参数remoteDir="+this.remoteDir+",files="+files);

}

}

public void upload(List<File> files,String remoteDir)throws Exception{

this.remoteDir = remoteDir;

this.upload(files);

}

public void upload(File file)throws Exception{

List<File> files = new ArrayList<File>();

files.add(file);

this.upload(files);

}

public OutputStream getOutputStream(String fileName)throws Exception{

OutputStream os = null;

this.connectServer();

// 1、设置远程FTP目录

try {

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

os = this.ftpClient.storeFileStream(fileName);

if(os== null) {

throw new RuntimeException("服务器上创建文件对象失败");

}

return os;

} catch (IOException e) {

logger.error("服务器上创建文件对象失败" + e.getMessage());

}

}

    public boolean isFileExist(String fileName)throws Exception{


    boolean result = false;

this.connectServer();

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return result;

}

// 3、检查文件是否存在

for (FTPFile file : ftpFiles) {

if(file.getName().equals(fileName)){

result = true;

break;

}

}

} catch (Exception e) {

logger.error("检查文件是否存在失败" + e.getMessage());

}


    return result;

    }


    public boolean isFileExistByRegExName(String fileName)throws Exception{


    boolean result = false;

this.connectServer();

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return result;

}

// 3、检查文件是否存在

for (FTPFile file : ftpFiles) {

if(file.getName().indexOf(fileName) != -1){

result = true;

break;

}

}

} catch (Exception e) {

logger.error("检查文件是否存在失败" + e.getMessage());

}


    return result;

    }

    public void closeConnect() {

        try {

        this.ftpClient.disconnect();

logger.info(" 关闭FTP连接!!! ");

} catch (IOException e) {

logger.warn(" 关闭FTP连接失败!!! ",e);

}

    }


public String getRemoteDir() {

return remoteDir;

}

public void setRemoteDir(String remoteDir) {

this.remoteDir = remoteDir;

}

public String getLocalPath() {

return localDir;

}

public void setLocalPath(String localPath) {

this.localDir = localPath;

}

public String getDownloadFileName() {

return downloadFileName;

}

public void setDownloadFileName(String downloadFileName) {

this.downloadFileName = downloadFileName;

}

public String getRegEx() {

return regEx;

}

public void setRegEx(String regEx) {

this.regEx = regEx;

}

@Override

public String toString() {

return "FTPUtil [host=" + this.host + ", port=" + this.port + ", username="

+ this.username + ", password=" + this.password + "]";

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容