最近工做中用到了 FTP 相关的操做,因此借此机会了解了下具体内容。html
关于 FTP 基础推荐阅读《使用 Socket 通讯实现 FTP 客户端程序》,其中须要特别注意的是主动模式和被动模式,这一部分在平常使用中常常被忽略,但生产环境中可能会出问题,关键在于防火墙对端口的控制。java
程序操做 FTP 过程在上面推荐的文章中有所说起,你们能够看到过程仍是比较复杂的,不过好在有 apache 的 commons-net 给咱们提供了相关的工具类可使用,本文使用的是 3.6 版本。如下经过代码进行说明,此代码仅演示功能,不少地方并不完善,若是用做生产请自行修改。linux
/** * FTP发送至目标服务器 * @apiNote 依赖apache commons-net 包 * @param server */ public static void sendToServerByFTP(String server, int port, String username, String password, String encoding, String fileLocalPath, String fileRemotePath, String fileRemoteName) throws IOException { // 获取 FTPClient FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { System.out.println("connected failed"); } // 设置编码,当文件中存在中文且上传后文件乱码时可以使用此配置项 //ftpClient.setControlEncoding(encoding); // 切换为本地被动模式,能够解决FTP上传后文件为空的问题,但须要服务器将FTP服务添加至防火墙白名单 //ftpClient.enterLocalPassiveMode(); // 切换到指定目录 ftpClient.changeWorkingDirectory(fileRemotePath); // 获取文件并上传 File file = new File(fileLocalPath); InputStream inputStream = new FileInputStream(file); //文件名为中文名且上传后出现乱码时启用此项 //String fileName = new String(fileRemoteName.getBytes(encoding), "ISO8859-1"); boolean flag = ftpClient.storeFile(fileRemoteName, inputStream); // 关闭已占用资源 inputStream.close(); ftpClient.logout(); }
FTP 下载和上传基本步骤相似,依赖的方法由 storeFile 变为 retrieveFileapache
public void downloadFile(String server, int port, String username, String password, String serverPath, String localPath, String fileName) throws IOException { // 登陆 FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); // 验证登陆状况 int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new RuntimeException("登陆FTP服务器失败,错误代码:" + replyCode); } // 切换服务器至目标目录 ftpClient.changeWorkingDirectory(serverPath); // 下载文件 File file = new File(localPath); FileOutputStream fileOutputStream = new FileOutputStream(file); ftpClient.retrieveFile(fileName, fileOutputStream); // 关闭资源占用 fileOutputStream.close(); ftpClient.logout(); }
public void deleteFile(String server, int port, String username, String password, String serverPath, String fileName) throws IOException { // 登陆 FTPClient ftpClient = new FTPClient(); ftpClient.connect(server, port); ftpClient.login(username, password); // 验证登陆状况 int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { throw new RuntimeException("登陆FTP服务器失败,错误代码:" + replyCode); } ftpClient.changeWorkingDirectory(serverPath); ftpClient.deleteFile(fileName); }