Ftp上传文件
package net.util.common; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.net.ftp.FTPSClient; /** * need commons-net-3.5.jar */ public class FtpHelper { private String host;//ip地址 private Integer port;//端口号 private String userName;//用户名 private String pwd;//密码 //private String homePath;//aaa路径 private String charSet = "utf-8"; // 默认超时, 毫秒 private long timeout = 30*1000; public FTPClient ftpClient = null; public FtpHelper(){ init(); } public FtpHelper(boolean ftps){ init(ftps); } /** * ftp 初始化 */ public void init(){ init(false); } public void init(boolean ftps){ close(); if(ftps==true){ ftpClient = new FTPSClient(true); } else{ ftpClient=new FTPClient(); } // 默认编码 ftpClient.setControlEncoding(charSet); //ftpClient.setBufferSize(524288); //ftpClient.enterLocalPassiveMode(); // 毫秒计时 ftpClient.setDefaultTimeout((int) timeout); ftpClient.setConnectTimeout((int) timeout); //ftpClient.setSoTimeout((int) timeout); //ftpClient.setDataTimeout(timeout); } /** * 获取ftp连接 * @return * @throws Exception */ public boolean connect(String host, Integer port, String userName, String pwd) throws Exception{ this.host = host; this.port = port; this.userName= userName; this.pwd = pwd; return connect(); } public boolean connect() throws Exception{ boolean flag=false; int reply; if (port==null) { ftpClient.connect(host,21); }else{ ftpClient.connect(host, port); } flag = ftpClient.login(userName, pwd); if(flag==false) return flag; // 服务器是否响应 reply = ftpClient.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)==false) { flag = false; ftpClient.disconnect(); return flag; } // 默认文件格式 ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return flag; } /** * 关闭ftp连接 */ public void close(){ if (ftpClient==null || ftpClient.isConnected()==false) { ftpClient = null; return; } try { ftpClient.logout(); ftpClient.disconnect(); } catch (IOException e) { LogHelper.logger.warn("",e); } ftpClient = null; } /* * ftp 多种开关函数 */ public FTPClient getClient(){ return ftpClient; } public void setControlEncoding(String encoding) { this.charSet = encoding; ftpClient.setControlEncoding(encoding); } public void enterLocalPassiveMode(){ ftpClient.enterLocalPassiveMode(); } public void enterLocalActiveMode(){ ftpClient.enterLocalActiveMode(); } // 毫秒计时 public void setDefaultTimeout(int timeout) { ftpClient.setDefaultTimeout(timeout); } // 毫秒计时 // public void setConnectTimeout(int connectTimeout) { // ftpClient.setConnectTimeout(connectTimeout); // } // 毫秒计时 public void setDataTimeout(int timeout) { ftpClient.setDataTimeout(timeout); } public void setBufferSize(int bufSize) { ftpClient.setBufferSize(bufSize); } /** * 传输格式 * @param mode: FTPClient.BINARY_FILE_TYPE * @return * @throws IOException */ public boolean setFileTransferMode(int mode) throws IOException{ return ftpClient.setFileTransferMode(mode); } /** * 文件格式 * @param mode: FTPClient.BINARY_FILE_TYPE * @return * @throws IOException */ public boolean setFileType(int mode) throws IOException { return ftpClient.setFileType(mode); } /* * ftp 多种开关函数 */ /** * ftp创建目录 * @param path * @return * @throws IOException */ public boolean createDir(String path) throws IOException{ boolean bl = false; String pwd = "/"; try { pwd = ftpClient.printWorkingDirectory(); } catch (IOException e) { LogHelper.logger.warn("",e); } if(path.endsWith("/")==false){ path = path + "/"; } int fromIndex = 0; while(true){ int start = path.indexOf("/", fromIndex); if(start<0) break; fromIndex = start; String curPath = path.substring(0, fromIndex+1); //System.out.println(curPath); bl = ftpClient.changeWorkingDirectory(curPath); if(bl==false){ bl = ftpClient.makeDirectory(curPath); } if(bl==false) break; fromIndex = fromIndex + 1; } ftpClient.changeWorkingDirectory(pwd); return bl; } /** * ftp上传文件或文件夹 * @param srcPath: 本地目录或文件 * @param dstPath: ftp目录或文件 * @throws Exception */ public void upload(String localPath, String ftpPath) throws Exception{ File file = new File(localPath); if (file.isDirectory()) { createDir(ftpPath); String[] files=file.list(); for(String fileName : files){ String subLocalPath = PathUtil.CombineUrl(localPath, fileName); String subFtpPath = PathUtil.CombineUrl(ftpPath, fileName); upload(subLocalPath, subFtpPath); } } else{ FileInputStream localInput = null; try { //ftpClient.enterLocalPassiveMode(); String dirPath = new File(ftpPath).getParent(); dirPath = dirPath.replace("\\", "/"); createDir(dirPath); localInput = new FileInputStream(file); if(ftpClient.storeFile(ftpPath, localInput)==false){ LogHelper.logger.error("ftp upload file error: "+localPath); } } catch (Exception e) { LogHelper.logger.warn("",e); } finally{ try { if(localInput!=null) localInput.close(); } catch (Exception e) {} } } } /** * ftp单文件上传 * @param localPath * @param ftpPath * @return */ public boolean uploadFile(String localPath, String ftpPath){ boolean bl = false; File file = new File(localPath); if (file.isFile()) { FileInputStream localInput = null; try { //String tmpPath = ftpPath + ".tmp"; //ftpClient.enterLocalPassiveMode(); String dirPath = new File(ftpPath).getParent(); dirPath = dirPath.replace("\\", "/"); createDir(dirPath); localInput = new FileInputStream(file); if(ftpClient.storeFile(ftpPath, localInput)==false){ bl = false; LogHelper.logger.error("ftp upload file error: "+localPath); } else{ //bl = ftpClient.rename(tmpPath, ftpPath); bl = true; } } catch (Exception e) { LogHelper.logger.warn("",e); } finally{ try { if(localInput!=null) localInput.close(); } catch (Exception e) {} } } return bl; } /** * ftp下载文件或目录 * @param ftpPath: ftp远程目录或文件 * @param localPath: 本地保存目录或文件 * @param isFile: ftppath是文件或目录 * @throws Exception */ public void down(String ftpPath, String localPath, boolean isFile) throws Exception{ if(isFile==true){ FileOutputStream localFos = null; try { //ftpClient.enterLocalPassiveMode(); String dirPath = new File(localPath).getParent(); FileUtil.createDir(dirPath); File file = new File(localPath); localFos = new FileOutputStream(file); if(ftpClient.retrieveFile(ftpPath, localFos)==false){ LogHelper.logger.error("ftp down file error: "+ftpPath); } } catch (Exception e) { LogHelper.logger.warn("",e); } finally{ try { if(localFos!=null) localFos.close(); } catch (Exception e) {} } } // 目录处理 else{ FileUtil.createDir(localPath); FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath); for (int j=0; j<ftpFiles.length; j++) { FTPFile ftpFile = ftpFiles[j]; String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName()); String subLocalPath = PathUtil.CombineUrl(localPath, ftpFile.getName()); if(ftpFile.isFile()==true){ down(subFtpPath, subLocalPath, true); } else{ down(subFtpPath, subLocalPath, false); } } } } /** * ftp单文件下载 * @param ftpPath * @param localPath * @return */ public boolean downFile(String ftpPath, String localPath) { boolean bl = false; FileOutputStream localFos = null; try { //ftpClient.enterLocalPassiveMode(); FileUtil.createDir(localPath, true); File file = new File(localPath); localFos = new FileOutputStream(file); if(ftpClient.retrieveFile(ftpPath, localFos)==false){ LogHelper.logger.error("ftp down file error: "+ftpPath); } else{ bl = true; } } catch (Exception e) { LogHelper.logger.warn("",e); } finally{ try { if(localFos!=null) localFos.close(); } catch (Exception e) {} } return bl; } /** * 判断路径是否为ftp文件 * @param ftpPath * @return * @throws IOException */ public boolean isFile(String ftpPath) throws IOException{ if(ftpPath==null || ftpPath.endsWith("/")) return false; File f = new File(ftpPath); String lastName = f.getName(); String parentDir = f.getParent(); // 根目录没有上层目录 if(parentDir==null) return false; FTPFile[] ftpFiles = ftpClient.listFiles(parentDir); for (int j=0; j<ftpFiles.length; j++) { FTPFile ftpFile = ftpFiles[j]; if(ftpFile.isFile()==true && lastName.equals(ftpFile.getName())){ return true; } } return false; } /** * 判断路径是否为ftp目录 * @param ftpPath * @return * @throws IOException */ public boolean isDir(String ftpPath) throws IOException{ if(ftpPath==null) return false; File f = new File(ftpPath); String lastName = f.getName(); String parentDir = f.getParent(); // 根目录没有上层目录 if(parentDir==null) return true; FTPFile[] ftpFiles = ftpClient.listFiles(parentDir); for (int j=0; j<ftpFiles.length; j++) { FTPFile ftpFile = ftpFiles[j]; if(ftpFile.isDirectory()==true && lastName.equals(ftpFile.getName())){ return true; } } return false; } public boolean isDirB(String ftpPath) { String cwd = "/"; try { cwd = ftpClient.printWorkingDirectory(); } catch (IOException e) { LogHelper.logger.warn("",e); } try { boolean isDir = ftpClient.changeWorkingDirectory(ftpPath); ftpClient.changeWorkingDirectory(cwd); return isDir; }catch (IOException e) {} return false; } /** * 返回指定目录文件列表(包括子目录) * @param ftpPath: ftp文件夹目录, 不能传文件 * @return * @throws Exception */ public List<String> listFtpFiles(String ftpPath) throws Exception{ List<String> list = new ArrayList<String>(); FTPFile[] ftpFiles = ftpClient.listFiles(ftpPath); for (int j=0; j<ftpFiles.length; j++) { FTPFile ftpFile = ftpFiles[j]; String subFtpPath = PathUtil.CombineUrl(ftpPath, ftpFile.getName()); if(ftpFile.isFile()==true){ list.add(subFtpPath); } else{ List<String> subList = listFtpFiles(subFtpPath); list.addAll(subList); } } return list; } /** * 返回当前目录文件列表 * @param ftpPath * @return * @throws IOException */ public FTPFile[] listFiles(String ftpPath) throws IOException{ return ftpClient.listFiles(ftpPath); } /** * ftp修改文件名 * @param from * @param to * @return */ public boolean rename(String from, String to){ boolean bl = false; try { bl = ftpClient.rename(from, to); } catch (IOException e) { LogHelper.logger.warn("",e); } return bl; } /** * 删除文件 * @param ftpPath * @return */ public boolean deleteFile(String ftpPath){ boolean bl = false; try { bl = ftpClient.deleteFile(ftpPath); } catch (IOException e) { LogHelper.logger.warn("",e); } return bl; } public void test() throws Exception{ //down("/tt/ss/msgutil.zip.tmp", "/root/Desktop/tmp/", true); down("/tt", "/root/Desktop/tmp/", false); ftpClient.rename("from", "to"); FTPFile[] files = ftpClient.listFiles(""); for(FTPFile ff : files){ System.out.println(ff.getName()); System.out.println(ff.getLink()); } System.out.println(files); } // test public static void main(String[] args) throws Exception { //FtpHelper fh = new FtpHelper("192.169.126.100",21,"yfsb","inet-eyed20"); FtpHelper fh = new FtpHelper(); boolean bl = fh.connect("172.16.9.101",21,"test1","111"); System.out.println("connect: "+bl); List<String> list = fh.listFtpFiles("/"); fh.uploadFile("C:/Users/wang/Desktop/testftp/tiedel.zip", "/tiedel.zip.tmp"); fh.deleteFile("/tiedel.zip"); bl = fh.rename("/tiedel.zip.tmp", "/tiedel.zip"); bl = fh.isFile("/33"); bl = fh.isDir("/tiedel.zip"); //fh.down("/p1/fp", "C:/Users/wang/Desktop/testftp22/tmp", false); //fh.test(); //bl = fh.createDir("/p1/p2/p3/p4/p5"); //fh.upload("/root/Desktop/friendxml0.txt"); //fh.upload("/root/Desktop/123", "/tt/ss2/"); System.out.println(bl); } }