Java使用FTPClient上传下载文件
package com.founder.mrp.util; import com.founder.mrp.util.storage.StorageFile; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import java.io.*; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; public class FtpUtil { /** * 获取FTPClient对象 * * @param ftpHost FTP主机服务器 * @param ftpPassword FTP 登录密码 * @param ftpUserName FTP登录用户名 * @param ftpPort FTP端口 默认为21 * @return */ public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) { FTPClient ftpClient = new FTPClient(); try { ftpClient = new FTPClient(); ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器 ftpClient.login(ftpUserName, ftpPassword);// 登录FTP服务器 if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { System.out.println("未连接到FTP,用户名或密码错误。"); ftpClient.disconnect(); } else { System.out.println("FTP连接成功。"); } } catch (SocketException e) { e.printStackTrace(); System.out.println("FTP的IP地址可能错误,请正确配置。"); } catch (IOException e) { e.printStackTrace(); System.out.println("FTP的端口错误,请正确配置。"); } return ftpClient; } /* * 从FTP服务器下载文件 * * @param ftpHost FTP IP地址 * @param ftpUserName FTP 用户名 * @param ftpPassword FTP用户名密码 * @param ftpPort FTP端口 * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa * @param localPath 下载到本地的位置 格式:H:/download * @param fileName 文件名称 */ public static void downloadFtpFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String localPath, String fileName) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("UTF-8"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(ftpPath); File localFile = new File(localPath + File.separatorChar + fileName); OutputStream os = new FileOutputStream(localFile); ftpClient.retrieveFile(fileName, os); os.close(); ftpClient.logout(); } catch (FileNotFoundException e) { System.out.println("没有找到" + ftpPath + "文件"); e.printStackTrace(); } catch (SocketException e) { System.out.println("连接FTP失败."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("文件读取错误。"); e.printStackTrace(); } } /* * 从FTP服务器下载文件 * * @param ftpHost FTP IP地址 * @param ftpUserName FTP 用户名 * @param ftpPassword FTP用户名密码 * @param ftpPort FTP端口 * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa * @param localPath 下载到本地的位置 格式:H:/download * @param fileName 文件名称 */ public static void downloadFtpFileErp(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName, StorageFile targetFile) { FTPClient ftpClient = null; try { ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); ftpClient.setControlEncoding("GBK"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(new String(ftpPath.getBytes("GBK"), "ISO-8859-1")); targetFile.getParent().mkdirs(); try (OutputStream output = targetFile.getOutputStream(false); InputStream inStream = ftpClient.retrieveFileStream(new String(fileName.getBytes("GBK"), "ISO-8859-1"))) { byte[] buf = new byte[8192]; int n; while ((n = inStream.read(buf, 0, buf.length)) != -1) { output.write(buf, 0, n); } } } catch (FileNotFoundException e) { System.out.println("没有找到" + ftpPath + "文件"); e.printStackTrace(); } catch (SocketException e) { System.out.println("连接FTP失败."); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("文件读取错误。"); e.printStackTrace(); } finally { if (ftpClient != null) { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) { try{ // downLoadPDFByUrl("http://nps.fltrp.com:805/wycode/30328b575cbc2dd64a4a0cd7d33244f3.pdf", // "ELISA.pdf",null); String ftpHost ="172.19.42.87"; String ftpUserName = "administrator"; String ftpPassword = "Founder123"; int ftpPort = 21; String ftpPath = "\\20551630-8A2D-B95C-F07E-4A4128B6B499\\Store File\\Normalized File"; String fileName = "2187.pdf"; String filePath = "/"; String localPath = "D:\\"; File file =new File("D:\\data.xml"); FileInputStream inStream=new FileInputStream(file); //上传 uploadFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, fileName, inStream, filePath,0); //下载 downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName); }catch (Exception e) { // TODO: handle exception } // downloadFtpFileErp("172.19.45.56", "administrator", "Founder123!", 21, "F:/FTPtest", "", "新建文本文档"); // downloadFtpFile("172.19.45.56", "administrator", "Founder123!", 21, "F:/FTPtest", "F:/test", "新建文本文档.txt"); } /** * 从网络Url中下载文件 * @param urlStr * @param fileName uuid * @param savePath 服务器路径 * @throws IOException */ public static void downLoadPDFByUrl(String urlStr,String fileName,StorageFile targetFile){ URL url=null; HttpURLConnection conn=null; try { url = new URL(urlStr); conn = (HttpURLConnection)url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(5*1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 /*File saveDir = new File(savePath); if(!saveDir.exists()){ saveDir.mkdir(); } File file = new File(saveDir+ File.separator+fileName); FileOutputStream fos = new FileOutputStream(file);*/ targetFile.getParent().mkdirs(); OutputStream fos = targetFile.getOutputStream(false); fos.write(getData); if(fos!=null){ fos.close(); } if(inputStream!=null){ inputStream.close(); } System.out.println("info:"+url+" download success"); } catch (FileNotFoundException e) { System.out.println("没有找到文件"); e.printStackTrace(); } catch (SocketException e) { System.out.println("网络连接失败"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); System.out.println("文件读取错误。"); e.printStackTrace(); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } } /** * 从输入流中获取字节数组 * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } /** * Description: 向FTP服务器上传文件 * @param ftpHost FTP服务器hostname * @param ftpUserName 账号 * @param ftpPassword 密码 * @param ftpPort 端口 * @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa * @param fileName ftp文件名称 * @param input 文件流 * @return 成功返回true,否则返回false */ public static boolean uploadFile(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort, String ftpPath, String fileName,InputStream input,String filePath,long filesize) { boolean success = false; FTPClient ftpClient = null; String[] ftpPathDir=ftpPath.split("/");//ftp目录 String[] dir=filePath.split("/");//创建多级目录 try { int reply; ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort); reply = ftpClient.getReplyCode(); for(int i=1;i<ftpPathDir.length;i++){ ftpClient.makeDirectory(new String(ftpPathDir[i].getBytes("GBK"),"iso-8859-1")); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("GBK"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); //取消服务器获取自身Ip地址和提交的host进行匹配 当不一致时会抛出异常 ftpClient.setRemoteVerificationEnabled(false); ftpClient.changeWorkingDirectory(new String(ftpPathDir[i].getBytes("GBK"),"iso-8859-1")); } for(int i=0;i<dir.length;i++){ if(!dir[i].equals("")){ ftpClient.makeDirectory(new String(dir[i].getBytes("GBK"),"iso-8859-1")); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); return success; } ftpClient.setControlEncoding("GBK"); // 中文支持 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); ftpClient.changeWorkingDirectory(new String(dir[i].getBytes("GBK"),"iso-8859-1")); } } //默认FTP上传速度过慢,由于默认缓冲区大小1024字节,将缓冲区大小改为10M ftpClient.setBufferSize(1024*1024*10); ftpClient.storeFile(new String(fileName.getBytes("GBK"),"iso-8859-1"), input); input.close(); ftpClient.logout(); success = true; } catch (Exception e) { e.printStackTrace(); return success; } finally { if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ioe) { } } } return success; } }