FTP服务:Java使用FTP操作文件
Java使用FTP操作文件
通过java代码连接FTP服务,上传,下载等:
1.1. 导包
将commons-net-3.5.jar包。导入到eclipse的Java项目中。
下载commons-net-3.5.jar包下载地址:
http://commons.apache.org/proper/commons-net/download_net.cgi
1.2. Ftp工具类(java)
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileNotFoundException; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.net.URLEncoder; 9 import org.apache.commons.net.ftp.FTPClient; 10 import org.apache.commons.net.ftp.FTPReply; 11 import org.slf4j.Logger; 12 import org.slf4j.LoggerFactory; 13 import org.springframework.web.multipart.MultipartFile; 14 15 16 /** 17 * FTP服务工具类 18 * @author limingcheng 19 * 20 */ 21 public class FtpClientUtil { 22 private static final Logger logger = LoggerFactory.getLogger(FtpClientUtil.class); 23 24 // 初始化参数 25 private String username = ""; // 用户名 26 private String password = ""; // 密码 27 private String destPath = ""; // 目标文件路径 28 private String ftpHost = ""; // FTP服务的IP地址 29 private String ftpPort = ""; // FTP端口 30 private FTPClient ftpClient = null; // FTP实例 31 private String localCharset = "GBK"; // 本地编码格式 32 private String serverCharset = "ISO-8859-1"; // FTP服务器编码格式 33 34 35 /** 36 * 创建FTP实例 37 * @param ftpServer 38 * @param ftpPort 39 * @param username 40 * @param password 41 * @throws Exception 42 */ 43 public FtpClientUtil(String ftpHost, String ftpPort, String username, String password) throws Exception{ 44 this.username = username; 45 this.password = password; 46 this.ftpHost = ftpHost; 47 this.ftpPort = ftpPort; 48 this.ftpClient = new FTPClient(); 49 try { 50 this.ftpClient.connect(ftpHost, Integer.parseInt(ftpPort)); // 连接FTP服务器 51 this.ftpClient.setDataTimeout(18000); // 设置超时时间 52 this.ftpClient.login(username, password); // 登陆FTP服务器 53 int reply = this.ftpClient.getReplyCode(); // 返回代码 54 // 根据返回代码判断是否连接成功 55 if (!FTPReply.isPositiveCompletion(reply)) { 56 this.ftpClient.disconnect(); 57 throw new Exception("连接ftp服务器失败"); 58 } 59 this.ftpClient.enterLocalPassiveMode(); 60 this.ftpClient.setBufferSize(4096); 61 // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK) 62 if (FTPReply.isPositiveCompletion(this.ftpClient.sendCommand("OPTS UTF8", "ON"))) { 63 this.localCharset = "UTF-8"; 64 } 65 this.ftpClient.setControlEncoding(this.localCharset); // 设置编码格式 66 this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 67 68 } catch (Exception e) { 69 throw new Exception("连接ftp客户端失败"); 70 } 71 } 72 73 /** 74 * 关闭FTP连接 75 * @throws IOException 76 */ 77 public void close() throws IOException { 78 if (this.ftpClient.isConnected()) { 79 this.ftpClient.disconnect(); 80 } 81 } 82 83 /** 84 * 删除文件 85 * @param sourcePath 86 * @param filename 87 * @throws Exception 88 */ 89 public void deleteFile(String sourcePath, String filename) throws Exception { 90 sourcePath = sourcePath.replace("\\", "/"); // 源文件路径 91 try { 92 boolean cd = this.ftpClient.changeWorkingDirectory(new String(sourcePath.getBytes("GBK"), this.serverCharset)); 93 if (!cd) { 94 throw new Exception("切换到上传文件目录失败或者目录不存在!"); 95 } 96 String[] files = this.ftpClient.listNames(); 97 this.ftpClient.deleteFile(new String(filename.getBytes(this.localCharset), this.serverCharset)); 98 } catch (Exception e) { 99 throw new Exception("删除ftp文件失败,请检查参数配置和ftp服务器状态!"); 100 } 101 } 102 103 /** 104 * 上传文件 105 * @param sourcePath 106 * @throws Exception 107 */ 108 public void uploadFile(String sourcePath) throws Exception { 109 sourcePath = sourcePath.replace("\\", "/"); // 源文件路径 110 this.destPath = this.destPath.replace("\\", "/"); // 目标文件路径 111 FileInputStream fis = null; 112 String fileName = sourcePath.substring(sourcePath.lastIndexOf("/") + 1); // 文件名 113 try { 114 File localFile = new File(sourcePath); 115 fis = new FileInputStream(localFile); 116 String[] destpaths = this.destPath.split("/"); // 文件路径 117 // 根据文件路径长度判断是否需要创建文件夹 118 if (destpaths.length >= 2) { 119 for (int i = 1; i < destpaths.length; i++) { 120 String folderName = new String(destpaths[i].getBytes(this.localCharset), this.serverCharset); 121 this.ftpClient.makeDirectory(folderName); // 创建文件名 122 boolean flag = this.ftpClient.changeWorkingDirectory(folderName); // 跳转到对应的文件路径下 123 if (!flag) { 124 throw new Exception("切换目录失败,请检查目录是否存在!"); 125 } 126 } 127 } else { 128 String folderName = new String(this.destPath.getBytes(this.localCharset), this.serverCharset); 129 130 this.ftpClient.makeDirectory(folderName); 131 boolean flag = this.ftpClient.changeWorkingDirectory(folderName); 132 if (!flag) { 133 throw new Exception("切换目录失败,请检查目录是否存在!"); 134 } 135 } 136 // 保存文件 137 this.ftpClient.storeFile(new String(fileName.getBytes(this.localCharset), this.serverCharset), fis); 138 fis.close(); 139 } catch (Exception e) { 140 throw new Exception("上传ftp文件失败,请检查参数配置和ftp服务器状态!"); 141 } finally { 142 try { 143 if (fis != null) 144 fis.close(); 145 } catch (IOException e) { 146 e.printStackTrace(); 147 } 148 } 149 } 150 151 /** 152 * 上传文件 153 * @param ftpHost 154 * @param ftpUserName 155 * @param ftpPassword 156 * @param ftpPort 157 * @param ftpPath 158 * @param fileName 159 * @return 160 * @throws Exception 161 */ 162 public void uploadFile(String fileName, String ftpPath, MultipartFile file) throws Exception { 163 InputStream fis = null; 164 ftpPath = ftpPath.replace("\\", "/"); 165 ftpPath = ftpPath.substring(1, ftpPath.length()); 166 this.destPath = ftpPath; 167 try { 168 fis = file.getInputStream(); 169 String[] destpaths = this.destPath.split("/"); // 文件路径 170 // 根据文件路径长度判断是否需要创建文件夹 171 if (destpaths.length >= 2) { 172 for (int i = 1; i < destpaths.length; i++) { 173 String folderName = new String(destpaths[i].getBytes(this.localCharset), this.serverCharset); 174 this.ftpClient.makeDirectory(folderName); // 创建文件名 175 boolean flag = this.ftpClient.changeWorkingDirectory(folderName); // 跳转到对应的文件路径下 176 if (!flag) { 177 throw new Exception("切换目录失败,请检查目录是否存在!"); 178 } 179 } 180 } else { 181 String folderName = new String(this.destPath.getBytes(this.localCharset), this.serverCharset); 182 183 this.ftpClient.makeDirectory(folderName); 184 boolean flag = this.ftpClient.changeWorkingDirectory(folderName); 185 if (!flag) { 186 throw new Exception("切换目录失败,请检查目录是否存在!"); 187 } 188 } 189 // 保存文件 190 this.ftpClient.storeFile(new String(fileName.getBytes(this.localCharset), this.serverCharset), fis); 191 192 } catch (FileNotFoundException e) { 193 logger.error("没有找到" + ftpPath + File.separatorChar + fileName + "文件"); 194 e.printStackTrace(); 195 } catch (IOException e) { 196 e.printStackTrace(); 197 logger.error("文件读取错误。"); 198 e.printStackTrace(); 199 } finally { 200 if(fis!=null) { 201 try { 202 fis.close(); 203 } catch (IOException e) { 204 e.printStackTrace(); 205 } 206 } 207 } 208 } 209 210 211 212 /** 213 * 下载文件 214 * @param sourcePath 215 * @param filename 216 * @return 217 * @throws Exception 218 */ 219 public File downFile(String sourcePath, String filename) throws Exception { 220 sourcePath = sourcePath.replace("\\", "/"); // 源文件路径 221 OutputStream os = null; 222 File localFile = null; 223 try { 224 // 跳转到对应的文件路径中 225 boolean cd = this.ftpClient.changeWorkingDirectory(new String(sourcePath.getBytes(this.localCharset), 226 this.serverCharset)); 227 if (!cd) { 228 throw new Exception("切换到上传文件目录失败或者目录不存在!"); 229 } 230 localFile = new File(URLEncoder.encode(filename, "UTF-8")); 231 os = new FileOutputStream(localFile); 232 this.ftpClient.retrieveFile(new String(filename.getBytes(this.localCharset), this.serverCharset), os); 233 File localFile1 = localFile; 234 return localFile1; 235 } catch (Exception e) { 236 throw new Exception("下载ftp文件失败,请检查参数配置和ftp服务器状态!"); 237 } finally { 238 try { 239 if (os != null) 240 os.close(); 241 } catch (IOException e) { 242 throw new Exception("关闭输出流出错!"); 243 } 244 } 245 } 246 247 248 }