java ftp协议操作文件
package com.cmxcode.servicesgateway.util;
import lombok.extern.slf4j.Slf4j;
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 java.io.*;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class FTPUtils {
public FTPUtils() {
}
private static String localCharset = "GBK";
private static String serverCharset = "ISO-8859-1";
private static final String CHARSET_UTF8 = "UTF-8";
private static final String OPTS_UTF8 = "OPTS UTF8";
private static final int BUFFER_SIZE = 1024 * 1024 * 4;
private static FTPClient ftpClient = null;
public boolean downloadFile(String ftpPath, String fileName, String savePath) {
boolean flag = false;
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return flag;
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录不存在");
return flag;
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
if (ftpName.equals(fileName)) {
File file = new File(savePath + '/' + ftpName);
try {
OutputStream os = new FileOutputStream(file);
flag = ftpClient.retrieveFile(ff, os);
} catch (Exception e) {
log.error(e.getMessage());
}
break;
}
}
} catch (IOException e) {
log.error("下载文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return flag;
}
public boolean downloadFiles(String ftpPath, String savePath) {
boolean flag = false;
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return flag;
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
return flag;
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
File file = new File(savePath + '/' + ftpName);
try {
OutputStream os = new FileOutputStream(file);
ftpClient.retrieveFile(ff, os);
} catch (Exception e) {
log.error(e.getMessage() + e);
}
}
flag = true;
} catch (IOException e) {
log.error("下载文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return flag;
}
public Map<String, byte[]> getFileBytes(String ftpPath) {
Map<String, byte[]> map = new HashMap<String, byte[]>();
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return map;
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
return map;
}
for (String ff : fs) {
try {
InputStream is = ftpClient.retrieveFileStream(ff);
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int readLength = 0;
while ((readLength = is.read(buffer, 0, BUFFER_SIZE)) > 0) {
byteStream.write(buffer, 0, readLength);
}
map.put(ftpName, byteStream.toByteArray());
ftpClient.completePendingCommand();
} catch (Exception e) {
log.error(e.getMessage());
}
}
} catch (IOException e) {
log.error("获取文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return map;
}
public byte[] getFileBytesByName(String ftpPath, String fileName) {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return byteStream.toByteArray();
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
return byteStream.toByteArray();
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
if (ftpName.equals(fileName)) {
try {
InputStream is = ftpClient.retrieveFileStream(ff);
byte[] buffer = new byte[BUFFER_SIZE];
int len = -1;
while ((len = is.read(buffer, 0, BUFFER_SIZE)) != -1) {
byteStream.write(buffer, 0, len);
}
} catch (Exception e) {
log.error(e.getMessage() + e);
}
break;
}
}
} catch (IOException e) {
log.error("获取文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return byteStream.toByteArray();
}
public Map<String, InputStream> getFileInputStream(String ftpPath) {
Map<String, InputStream> map = new HashMap<String, InputStream>();
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return map;
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
return map;
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
InputStream is = ftpClient.retrieveFileStream(ff);
map.put(ftpName, is);
ftpClient.completePendingCommand();
}
} catch (IOException e) {
log.error("获取文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return map;
}
public InputStream getInputStreamByName(String ftpPath, String fileName) {
InputStream input = null;
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
return input;
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
return input;
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
if (ftpName.equals(fileName)) {
input = ftpClient.retrieveFileStream(ff);
break;
}
}
} catch (IOException e) {
log.error("获取文件失败" + e);
} finally {
Boolean connect = closeConnect();
log.info("连接关闭状态:" + connect);
}
}
return input;
}
public Map checkoutFtpPathAndFileName(String ftpPath, String fileName) {
Map<String, Boolean> map = new HashMap<String, Boolean>();
map.put("filePath", false);
map.put("fileName", false);
if (ftpClient != null) {
try {
String path = changeEncoding(ftpPath);
if (!ftpClient.changeWorkingDirectory(path)) {
log.error(ftpPath + "该目录不存在");
map.put("filePath", false);
} else {
map.put("filePath", true);
}
ftpClient.enterLocalPassiveMode();
String[] fs = ftpClient.listNames();
if (fs == null || fs.length == 0) {
log.error(ftpPath + "该目录下没有文件");
map.put("fileName", false);
}
for (String ff : fs) {
String ftpName = new String(ff.getBytes(serverCharset), localCharset);
if (ftpName.equals(fileName)) {
map.put("fileName", true);
}
}
} catch (IOException e) {
log.error("获取文件失败" + e);
}
}
return map;
}
public boolean deleteFile(String filePath) {
boolean flag = false;
if (ftpClient != null) {
try {
String path = changeEncoding(filePath);
flag = ftpClient.deleteFile(path);
} catch (IOException e) {
log.error("删除文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return flag;
}
public boolean deleteFiles(String dirPath) {
boolean flag = false;
if (ftpClient != null) {
try {
ftpClient.enterLocalPassiveMode();
String path = changeEncoding(dirPath);
String[] fs = ftpClient.listNames(path);
if (fs == null || fs.length == 0) {
log.error(dirPath + "该目录下没有文件");
return flag;
}
for (String ftpFile : fs) {
ftpClient.deleteFile(ftpFile);
}
flag = true;
} catch (IOException e) {
log.error("删除文件失败" + e);
} finally {
Boolean close = closeConnect();
log.info("连接是否关闭:" + close);
}
}
return flag;
}
public boolean uploadFile(String pathname, String fileName, InputStream inputStream) {
boolean flag = false;
if (ftpClient != null) {
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
log.info("上传文件成功");
flag = true;
} catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return flag;
}
public boolean uploadFile(String pathname, String fileName, String originfilename) {
boolean flag = false;
if (ftpClient != null) {
InputStream inputStream = null;
try {
log.info("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
CreateDirecroty(pathname);
ftpClient.enterLocalPassiveMode();
boolean storeFlag = ftpClient.storeFile(fileName, inputStream);
log.info("storeFlag==" + storeFlag);
inputStream.close();
ftpClient.logout();
log.info("上传文件成功");
flag = true;
} catch (Exception e) {
log.error("上传文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return flag;
}
public Boolean login(String address, int port, String username, String password) {
ftpClient = new FTPClient();
boolean flag = false;
try {
ftpClient.connect(address, port);
ftpClient.login(username, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
closeConnect();
log.error("FTP服务器连接失败:" + "地址:" + address + " 端口:" + port + " 用户名:" + username + " 密码:" + password);
} else {
flag = true;
}
} catch (Exception e) {
log.error("FTP登录失败" + e);
}
return flag;
}
public Boolean closeConnect() {
Boolean flag = false;
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.logout();
flag = true;
} catch (IOException e) {
log.error("关闭FTP连接失败" + e);
}
}
return flag;
}
private static String changeEncoding(String ftpPath) {
String directory = null;
try {
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
localCharset = CHARSET_UTF8;
}
directory = new String(ftpPath.getBytes(localCharset), serverCharset);
} catch (Exception e) {
log.error("路径编码转换失败" + e);
}
return directory;
}
private void createDirectorys(String dirPath) {
try {
if (!dirPath.endsWith("/")) {
dirPath += "/";
}
String directory = dirPath.substring(0, dirPath.lastIndexOf("/") + 1);
ftpClient.makeDirectory("/");
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
while (true) {
String subDirectory = new String(dirPath.substring(start, end));
if (!ftpClient.changeWorkingDirectory(subDirectory)) {
if (ftpClient.makeDirectory(subDirectory)) {
ftpClient.changeWorkingDirectory(subDirectory);
} else {
log.error("创建目录失败");
return;
}
}
start = end + 1;
end = directory.indexOf("/", start);
if (end <= start) {
break;
}
}
} catch (Exception e) {
log.error("上传目录创建失败" + e);
}
}
public boolean changeWorkingDirectory(String directory) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
log.info("进入文件夹" + directory + " 成功!");
} else {
log.error("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
public boolean existFile(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
public boolean makeDirectory(String dir) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
log.info("创建文件夹" + dir + " 成功!");
} else {
log.error("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
private boolean CreateDirecroty(String remote) throws IOException {
boolean success = true;
String directory = remote + "/";
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path)) {
if (makeDirectory(subDirectory)) {
changeWorkingDirectory(subDirectory);
} else {
log.error("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory);
}
} else {
changeWorkingDirectory(subDirectory);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
if (end <= start) {
break;
}
}
}
return success;
}
public void getFileSize() throws IOException {
if (ftpClient != null) {
FTPFile[] files = null;
Long fileSize = -1L;
ftpClient.setControlEncoding("GBK");
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setBufferSize(BUFFER_SIZE);
files = ftpClient.listFiles("voice/test.mp3");
if(null != files && files.length > 0)
{
fileSize = files[0].getSize();
}
System.out.println(fileSize);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
ftpClient.disconnect();
}
}
}
}