1. 程式人生 > >Java操作ftpClient常用方法

Java操作ftpClient常用方法

package com.common.service.impl;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Service;
import com.common.service.FtpService;
import com.pojo.FtpModel;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@Service
public class FtpServiceImpl implements FtpService {
ThreadLocal<FTPClient> threadFtpClient = new ThreadLocal<FTPClient>();

public FtpServiceImpl() {
super();
init();
}

private void init() {
log.info("初始化 ---------ftp連結資料---------");
}
        //獲取ftp連線
public FTPClient getFTPClient() {
FTPClient ftpClient = threadFtpClient.get();
if (ftpClient == null) {
throw new RuntimeException("連線已被關閉!");
}
return ftpClient;
}
        
public void login(FtpModel ftpModel) throws IOException {
{
FTPClient ftpClient = null;
try {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("GBK");
ftpClient.connect(ftpModel.getFtpHost(), ftpModel.getFtpPort());// 連線FTP伺服器
ftpClient.login(ftpModel.getFtpUserName(), ftpModel.getFtpPassword());// 登陸FTP伺服器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
log.info("未連線到FTP,使用者名稱或密碼錯誤。");
ftpClient.disconnect();
} else {
log.info("FTP連線成功。");
threadFtpClient.set(ftpClient);
}
} catch (SocketException e) {
log.info("FTP的IP地址可能錯誤,請正確配置。");
throw new IOException(e.getMessage());
}
}
}
     
@Override
public void uploadFile(InputStream file, String fileName) throws IOException {
String Uuid = UUID.randomUUID().toString().replace("-", "");
String tmpFileName = Uuid + ".tmp";
FTPClient ftpClient = getFTPClient();
ftpClient.setBufferSize(1024);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(tmpFileName, file);
ftpClient.rename(tmpFileName, fileName);
}
        
public List<String> ls() throws IOException {
FTPClient ftpClient = getFTPClient();
List<String> fileList = new ArrayList<>();
FTPFile[] listDirectories = ftpClient.listFiles();
for (FTPFile ftpFile : listDirectories) {
String name = ftpFile.getName();
fileList.add(name);
}
return fileList;
}

@Override
public void download(String fileName, File localFile) throws IOException {
FileOutputStream os = new FileOutputStream(localFile);
try {
FTPClient ftpClient = getFTPClient();
ftpClient.retrieveFile(fileName, os);
} finally {
os.close();
}
}

@Override
public void delete(String fileName) throws IOException {
FTPClient ftpClient = getFTPClient();
ftpClient.deleteFile(fileName);
}

@Override
public void cd(String path) throws IOException {
// TODO Auto-generated method stub
FTPClient ftpClient = getFTPClient();
ftpClient.changeWorkingDirectory(path);
}

@Override
public void mv(String fileName, String path) throws IOException {
// TODO Auto-generated method stub
FTPClient ftpClient = getFTPClient();
path= path+ fileName;
boolean flag = ftpClient.rename(fileName, path);
log.info("mvFile結果:" + flag);
}

@Override
public void cpFile(String fileName, String cpFileName) throws IOException {
FTPClient ftpClient = getFTPClient();
InputStream is = null;
try {
// 設定以二進位制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 下載
is = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"), "iso-8859-1"));
// 主動呼叫一次getReply()把接下來的226消費掉. 這樣做是可以解決這個返回null問題
ftpClient.getReply();
if (is != null) {
ftpClient.storeFile(new String(cpFileName.getBytes("GBK"), "iso-8859-1"), is);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
is.close();
}
}
}

    @Override
public void logout() {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient();
if (ftpClient != null) {
ftpClient.logout();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
threadFtpClient.remove();
} catch (IOException e) {
log.error("刪除ftp連結失敗");
}
}
}
}

}

附上ftpClient文件地址:http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html