62,614
社区成员
发帖
与我相关
我的任务
分享
public String download(String localPath, String remotePath) {
FileOutputStream fos = null;
try {
File localFile = new File(localPath);
File parent = localFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
} else {
if (localFile.exists()) {
localFile.delete();
}
}
fos = new FileOutputStream(localFile);
client.setBufferSize(1024);
client.setControlEncoding("UTF-8");
client.enterLocalPassiveMode();// 进入被动模式
client.setFileType(FTP.BINARY_FILE_TYPE);// 使用二进制文件文件类型
if (client.retrieveFile(remotePath, fos)) {
return "true";
} else {
logger.error("FTP 下载文件失败!");
}
} catch (IOException e) {
logger.error("FTP 下载文件出错!", e);
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "false";
}
package com.cn.sjd;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
/**
* Apache commons-net 试用一把,看看FTP客户端工具做的好用不
*
*/
public class FtpTest {
public static void main(String[] args) {
testUpload();
// testDownload();
}
/**
* FTP上传单个文件测试
* 1.连接服务
* 2.确定你要上传的文件
* 3.指定你在服务器端存放的位置
*/
public static void testUpload() {
FTPClient ftpClient = new FTPClient();
FileInputStream fis = null;
try {
ftpClient.connect("192.168.1.111");
ftpClient.login("admin", "javaf");
File srcFile = new File("F:\\images\\460.jpg");
fis = new FileInputStream(srcFile);
//设置上传目录
ftpClient.changeWorkingDirectory("/lanjie/pic");
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile("work.jpg", fis);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fis);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
/**
* FTP下载单个文件测试
*/
public static void testDownload() {
FTPClient ftpClient = new FTPClient();
FileOutputStream fos = null;
try {
ftpClient.connect("192.168.1.111");
ftpClient.login("admin", "javaf");
String remoteFileName = "/lanjie/pic/girl.jpg";
fos = new FileOutputStream("c:/down.jpg");
ftpClient.setBufferSize(1024);
//设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remoteFileName, fos);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fos);
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", e);
}
}
}
}