2023.08.07 | admin | 112次围观
轻松愉快搞定ftp上传下载文件,这里推荐使用hutool的工具类,本人实测超级好用几行代码搞定。
1、项目maven引入hutool依赖包ftp上传文件没有内容,我这里用的5.3.4的包
cn.hutool
hutool-all
5.3.4
2、上传文件
public static void main(String[] args) throws IOException {
String remotePath ="/test/a.txt";
String localPath ="d://a.txt";
Ftp ftp = null;
try {
//建立FTP连接
ftp = new Ftp("127.0.0.1",22,"test", "test", Charset.defaultCharset(), FtpMode.Passive);
boolean isUp = ftp.upload(remotePath, FileUtil.file(localPath));
if (isUp) System.out.println("文件上传成功");
}catch (Exception e){
e.printStackTrace();
}finally {
//释放ftp连接
if (ftp!=null){
ftp.close();
}
}
}
}
3、下载文件
public static void main(String[] args) throws IOException {
String remotePath ="/test/a.txt";
String localPath ="d://a.txt";
Ftp ftp = null;
try {
//建立FTP连接
ftp = new Ftp("127.0.0.1",22,"test", "test", Charset.defaultCharset(), FtpMode.Passive);
ftp.download(remotePath,"a.txt",FileUtil.file(localPath));
if (FileUtil.file(localPath).exists()){
System.out.println("文件下载成功");
}
}catch (Exception e){
e.printStackTrace();
}finally {
//释放ftp连接
if (ftp!=null){
ftp.close();
}
}
}
注:结尾一定要记得关闭ftp连接ftp上传文件没有内容,上传文件和下载文件可以选择使用主动模式还是被动模式,主动模式,不过试试建议使用被动模式,主动模式容易被防火墙拦截
版权声明
本文仅代表作者观点。
本文系作者授权发表,未经许可,不得转载。
发表评论