1. 首先先配置ftp服务器
可参考:https://www.cnblogs.com/popfisher/p/7992036.html
2. 需要依赖:commons-net,版本3.6
gradle添加依赖
compile group: 'commons-net', name: 'commons-net', version: "3.6"
3. 代码实现
/**
* 使用 FTP 实现文件上传下载
*/
public static boolean uploadFile(String hostname, int port, String username, String password, String pathname,
String fileName, InputStream inputStream) {
boolean flag = false;
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("UTF-8");
try {
// 连接FTP服务器
ftpClient.connect(hostname, port);
// 登录FTP服务器
ftpClient.login(username, password);
// 是否成功登录FTP服务器
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
ftpClient.disconnect();
return flag;
}
// 设置传输二进制文件
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
public static boolean downloadFile(String hostname, int port, String username, String password, String pathname,
String filename, String localpath) {
boolean flag = false;
FTPClient ftpClient = new FTPClient();
try {
// 连接FTP服务器
ftpClient.connect(hostname, port);
// 登录FTP服务器
ftpClient.login(username, password);
// 验证FTP服务器是否登录成功
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
return flag;
}
// 切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
File localFile = new File(localpath + "/" + file.getName());
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
ftpClient.logout();
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
}
}
}
return flag;
}
4.
设置连接超时和数据传输超时,对于性能有要求的项目,设置这两个属性很重要
例如,设置为60秒:
ftpClient.setDataTimeout(60000); //设置传输超时时间为60秒
ftpClient.setConnectTimeout(60000); //连接超时为60秒
5.
需要注意的是,ftp.isConnected最好要写在finally里面,不要直接写在ftp.logout()后面
因为这样子写会有很大的隐患,查看org.apache.commons.net的API,可以看到,FTPClient的logout()也
会抛出IOException的。
如上述代码的直接后果就是,Ftpclient对象退出异常,连接没有释放。积少成多,也会慢慢阻塞FTP服务器的
连接,最终引发连接异常。
java实现ftp文件上传,下载
最新推荐文章于 2024-05-31 17:44:25 发布