解决java ftp 下载中文文件名乱码,0字节问题,
public class FTPUtil {
private String CHARSET = "GBK";
// private String CHARSET = System.getProperty("file.encoding");
/**
* 设置缓冲区大小4M
**/
private int BUFFER_SIZE = 1024 * 1024 * 4;
private FTPClient ftpClient = null;
public void login(String address, int port, String username, String password) {
ftpClient = new FTPClient();
try {
ftpClient.connect(address, port);
ftpClient.login(username, password);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 限制缓冲区大小
ftpClient.setBufferSize(BUFFER_SIZE);
ftpClient.enterLocalPassiveMode();
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpLogOut();
}
//这里设置GBK
ftpClient.setControlEncoding(CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @退出关闭服务器链接
*/
public void ftpLogOut() {
if (null != this.ftpClient && this.ftpClient.isConnected()) {
try {
boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
if (reuslt) {
// logger.info("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
// logger.warn("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
// logger.warn("关闭FTP服务器的连接异常!");
}
}
}
}
public boolean downloadFile(String remoteFileName, String localDires, String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
// File file = new File(strFilePath);
try {
// if (!file.exists()) {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));
//注意这里gbk和iso-8859-1
success = this.ftpClient.retrieveFile(new String(remoteFileName.getBytes(CHARSET), "iso-8859-1"), outStream);
if (success == true) {
return success;
}
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/***
* @下载文件夹
*/
public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
try {
String fileName = new File(remoteDirectory).getName();
localDirectoryPath = localDirectoryPath + fileName + "//";
// new File(localDirectoryPath).mkdirs();
File file = new File(localDirectoryPath);
if (!file.exists()) {
file.mkdir();
}
FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
String strremoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath, strremoteDirectoryPath);
}
}
} catch (IOException e) {
e.printStackTrace();
// logger.info("下载文件夹失败");
return false;
}
return true;
}
}