/**
* 将指定文件目录下的多个文件复制到另一个指定文件中
* @param fileNames 要复制的文件名
* @param fromPath 从哪个文件目录中复制
* @param toPath 复制到哪个目录
* @return true-复制成功,false-复制失败
* @throws IOException
*/
public boolean batchCopyFileToPath(List<String> fileNames, String fromPath, String toPath) throws IOException{
// 连接FTP服务器
FTPClient ftpClient = FTPClientConn();
// 判断否连接上
if(!ftpClient.isConnected()){
return false;
}
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setBufferSize(1024);
ftpClient.enterLocalPassiveMode();
// 判断文件夹是否存在,如不存在则创建文件夹
boolean isChangeWork = ftpClient.changeWorkingDirectory(toPath);
if (!isChangeWork) {
FtpCilentUtil.CreateDirecroty(toPath, ftpClient);
}
// 复制文件
for(String fileName : fileNames){
InputStream ins = null;
if(ftpClient.changeWorkingDirectory(formatPath(fromPath))){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ftpClient.retrieveFile(fileName, outputStream);
ins = new ByteArrayInputStream(outputStream.toByteArray());
}
if(ftpClient.changeWorkingDirectory(formatPath(toPath))){
if(!ftpClient.storeFile(fileName,ins)){
return false;
}
}
if(ins != null){
ins.close();
}
}
// 关闭连接
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return true;
}
private String formatPath(String filePath){
if(StringUtils.isBlank(filePath)){
filePath = "/";
}else{
filePath = "/" + filePath;
}
if(!filePath.endsWith("/")){
filePath += "/";
}
return filePath;
}
JAVA将FTP服务器指定文件目录下的多个文件复制到另一个指定文件中(已解决卡死现象)
于 2022-11-02 10:16:06 首次发布