已解决
springboot整合FTP实现文件传输
来自网友在路上 197897提问 提问时间:2023-11-03 05:31:51阅读次数: 97
最佳答案 问答题库978位专家为你答疑解惑
实现ftp文件传输的步骤:
1.ftp绑定ip端口登录
2.切换到指定地址
3.文件下载
4.关闭ftp连接
项目中使用的jar包
<!-- ftp包--><dependency><groupId>commons-net</groupId><artifactId>commons-net</artifactId><version>3.9.0</version></dependency>
项目中使用ftp代码:
public void getQxjFile() throws IOException {FTPClient ftpClient = new FTPClient(); //创建FTP连接客户端ftpClient.enterLocalPassiveMode();// 设置被动模式//ftp设置ip,端口ftpClient.connect(costomDefineData.getQxjIp(), Integer.parseInt(costomDefineData.getQxjPort()));//设置调用为被动模式ftpClient.enterLocalPassiveMode();//ftpClient.enterLocalActiveMode(); 设置为主动模式 //设置文件以二进制文件模式传输ftpClient.setFileType(FTP.BINARY_FILE_TYPE);//ftp登录boolean loggedIn = ftpClient.login(costomDefineData.getQxjUserName(), costomDefineData.getQxjPassword());if (loggedIn) {System.out.println("登录成功");} else {System.out.println("登录失败");}//切换到登录后的文件夹 这里指定ftp服务器文件存放位置boolean changed = ftpClient.changeWorkingDirectory("/");if (changed) {//获取到对应的FTP文件 这是获取对应文件夹下全部文件FTPFile[] files = ftpClient.listFiles();System.out.println("获取文件个数" + files.length);for (FTPFile file : files) {if (file.isFile()) {File localDir = new File(costomDefineData.getQxjFilePath() + YM + "/" + Day);if (!localDir.exists()) {localDir.mkdirs();}File localFile = new File(costomDefineData.getQxjFilePath() + YM + "/" + Day + "/" + file.getName());if (!localFile.exists()) {localFile.createNewFile();}//将ftp服务器上文件同步到本地ftpClient.retrieveFile("/" + file.getName(), new FileOutputStream(localFile));BufferedReader reader = new BufferedReader(new FileReader(localFile));// 读取文件内容并解析String line;String result = "";while ((line = reader.readLine()) != null) {// 解析每一行的数据result = result + line;}}}//实现ftp上文件删除boolean deleted = ftpClient.deleteFile("/" + file.getName());}//ftp用户登出ftpClient.logout();//ftp去掉链接ftpClient.disconnect(); }
使用ftp实现上传功能
public class FTPExample {public static void main(String[] args) {FTPClient ftpClient = new FTPClient();// 连接和登录代码省略try {// 上传文件File localFile = new File("local-file.txt");String remoteFile = "remote-file.txt";FileInputStream inputStream = new FileInputStream(localFile);boolean uploaded = ftpClient.storeFile(remoteFile, inputStream);inputStream.close();if (uploaded) {System.out.println("文件上传成功!");} else {System.out.println("文件上传失败!");}} catch (IOException e) {e.printStackTrace();} finally {// 断开连接代码省略}}
}
查看全文
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"springboot整合FTP实现文件传输":http://eshow365.cn/6-30798-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 使用Redis实现延迟队列
- 下一篇: 语言模型和人类的推理都依赖内容