JDK1.7 ftpclient的方法示例

2017-3-8来源:ASP.NET技巧人气:564

程序升级JDK7发现ftp下载存在与JDK6不兼容的问题,看了下网上的示例,没有找到API接口文档,自己凭借不是很好的英文看了下接口API,

提供一下示例,有问题请指出

package com.util; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.util.FileUtil; import sun.net.TelnetInputStream; import sun.net.TelnetOutputStream; import sun.net.ftp.FtpClient; import sun.net.ftp.FtpClient.TransferType; import sun.net.ftp.FtpPRotocolException; public class FtpUtilsJDK7 { private static Log log = LogFactory.getLog(FtpUtils.class); public FtpClient ftpClient = null; /** * connectServer 连接ftp服务器 * * @throws java.io.IOException * @param path * 文件夹,空代表根目录 * @param passWord * 密码 * @param user * 登陆用户 * @param server * 服务器地址 * @throws FtpProtocolException */ public void connectServer(String server, int port, String user, String password, String path) throws IOException, FtpProtocolException { this.connectServer(server, port, user, password, path, null); } /** * connectServer 连接ftp服务器 * * @param server * @param path * 文件夹,空代表根目录 * @param password * 密码 * @param user * 登陆用户 * @param server * 服务器地址 * @param send * @throws IOException * @throws FtpProtocolException */ public void connectServer(String server, int port, String user, String password, String path, String send) throws IOException, FtpProtocolException { // server:FTP服务器的ip地址;user:登录FTP服务器的用户名 // password:登录FTP服务器的用户名的口令;path:FTP服务器上的路径 ftpClient =FtpClient.create(); if(port == -1) { ftpClient.connect(new InetSocketAddress(server, port)); } else { ftpClient.connect(new InetSocketAddress(server, port)); } ftpClient.login(user, password.toCharArray()); // path是ftp服务下主目录的子目录 if(path.length() != 0) // ftpClient.cd(path); ftpClient.changeDirectory(path); // 用2进制上传、下载 ftpClient.setBinaryType(); // if(StringUtils.isNotEmpty(send)) { // ftpClient.sendServer(send); // } } /** * upload 上传文件 * * @throws java.lang.Exception * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小 * @param newname * 上传后的新文件名 * @param filename * 上传的文件 */ public long upload(String filename, String newname) throws Exception { long result = 0; TelnetOutputStream os = null; FileInputStream is = null; try { java.io.File file_in = new java.io.File(filename); if(!file_in.exists()) return -1; if(file_in.length() == 0) return -2; // os = ftpClient.putFileStream(newname); os = (TelnetOutputStream) ftpClient.putFileStream(newname, true); result = file_in.length(); is = new FileInputStream(file_in); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } } finally { if(is != null) { is.close(); } if(os != null) { os.close(); } } return result; } /** * upload * * @throws java.lang.Exception * @return * @param filename */ public long upload(String filename) throws Exception { String newname = ""; if(filename.indexOf("/") > -1) { newname = filename.substring(filename.lastIndexOf("/") + 1); } else { newname = filename; } return upload(filename, newname); } /** * download 从ftp下载文件到本地 * * @throws java.lang.Exception * @return * @param newfilename * 本地生成的文件名 * @param filename * 服务器上的文件名 */ public long download(String filename, String newfilename) throws Exception { long result = 0; TelnetInputStream is = null; FileOutputStream os = null; try { // is = ftpClient.get(filename); is = (TelnetInputStream) ftpClient.getFileStream(filename); java.io.File outfile = new java.io.File(newfilename); os = new FileOutputStream(outfile); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); result = result + c; } } catch (IOException e) { } finally { if(is != null) { is.close(); } if(os != null) { os.close(); } } return result; } /** * 重命名文件名称 * * @param oldName * @param newName * @return */ public boolean rename(String oldName, String newName) { boolean isSuccess = false; try { ftpClient.rename(oldName, newName); isSuccess = true; } catch (IOException e) { }catch (FtpProtocolException e) { } return isSuccess; } /** * 取得某个目录下的所有文件列表,包括文件夹; * * @param path * @return */ public List getFileList(String path) { List list = new ArrayList(); try { DataInputStream dis = new DataInputStream(ftpClient.nameList(path)); String filename = ""; while ((filename = dis.readLine()) != null) { list.add(filename); } } catch (Exception e) { } return list; } public boolean isExistsFile(String path, String file) { List<String> fileList = this.getFileList(path); if(fileList != null && fileList.size() > 0) { for(String f : fileList) { if(f.equals(file)) { return true; } } } return false; } /** * closeServer 断开与ftp服务器的链接 * * @throws java.io.IOException */ public void closeServer() throws IOException { try { if(ftpClient != null) { ftpClient.close(); } } catch (IOException e) { } } public boolean isFile(String fileName) { // boolean isFile = false; // TelnetInputStream oTelnetInputStream = null; // try { // oTelnetInputStream = ftpClient.get(fileName); // byte[] bytes = new byte[1024]; // int c = -1; // if ((c = oTelnetInputStream.read(bytes)) != -1) { // isFile = true; // } // } catch (java.io.FileNotFoundException fe) { // } catch (IOException ioe) { // io // } catch (Exception e) { // } // finally { // if (oTelnetInputStream != null) { // try { // oTelnetInputStream.close(); // } catch (IOException e) { // // } // } // } // return isFile; return !isDir(fileName); } public boolean isDir(String fileName) { boolean isDir = false; TelnetInputStream oTelnetInputStream = null; String strPath = null; try { // strPath = ftpClient.pwd(); strPath =ftpClient.getWorkingDirectory(); ftpClient.changeDirectory(fileName); ftpClient.changeToParentDirectory(); // ftpClient.cdUp(); isDir = true; } catch (Exception e) { log.error("获取文件出错,文件名:" + fileName); log.error("获取文件出错,原因为:" + e.getMessage(), e); } finally { if(strPath != null) { try { ftpClient.changeDirectory(strPath); } catch (Exception e) { } } } return isDir; } public void cd(String path) throws Exception { ftpClient.changeDirectory(path); } /** * upload 上传文件 * * @throws java.lang.Exception * @return -1 文件不存在 -2 文件内容为空 >0 成功上传,返回文件的大小 * @param newname * 上传后的新文件名 * @param filename * 上传的文件 */ public long uploadObyteFile(String filename, String newname) throws Exception { long result = 0; TelnetOutputStream os = null; FileInputStream is = null; try { java.io.File file_in = new java.io.File(filename); if(!file_in.exists()) return -1; // os = ftpClient.putFileStream(newname); os = (TelnetOutputStream) ftpClient.putFileStream(newname, true); result = file_in.length(); is = new FileInputStream(file_in); byte[] bytes = new byte[1024]; int c; while ((c = is.read(bytes)) != -1) { os.write(bytes, 0, c); } } finally { if(is != null) { is.close(); } if(os != null) { os.close(); } } return result; } public void mkdir(String path, String dir) throws Exception { //切换到文件夹下 ftpClient.changeDirectory(path); //创建远程文件夹 if(dir.contains("/")) { String[] dirArray = dir.split("/"); for(String d : dirArray) { if(d != null && !"".equals(d)) { ftpClient.makeDirectory(dir); // ftpClient.sendServer("mkdir " + dir + "/r/n"); // ftpClient.siteCmd("mkdir " + dir + "/r/n"); ftpClient.changeDirectory(d); } } } // 这个方法必须在 这两个方法中间调用 否则 命令不管用 ftpClient.setBinaryType(); ftpClient.getLastResponseString(); // ftpClient.readServerResponse(); } public void rmdir(String path, String dir) throws Exception { //切换到文件夹下 ftpClient.changeDirectory(path); //创建远程文件夹 ftpClient.removeDirectory(dir); // ftpClient.sendServer("rm -rf " + dir + "/r/n"); // 这个方法必须在 这两个方法中间调用 否则 命令不管用 ftpClient.setBinaryType(); ftpClient.getLastResponseString(); // ftpClient.readServerResponse(); } /** * 设置传输协议类型,如被动传输模式:"quote PASV" * 主动模式需要客户端必须开放端口给服务器,很多客户端都是在防火墙内,开放端口给FTP服务器访问比较困难。 * 被动模式只需要服务器端开放端口给客户端连接就行了。 * @param transferProtocolType * @throws IOException * @throws FtpProtocolException */ public void setTransferProtocolType(String transferProtocolType) throws FtpProtocolException, IOException { ftpClient.enablePassiveMode(true); // this.ftpClient.sendServer(transferProtocolType); } /** * @param file 提交的文件 * @param basePath 文件所在的本地路径 上传成功时会删除本地文件 * @param fileName 上传文件的文件名称 * @param remotePath 服务器文件的地址 */ public void uploadFile(File file,String basePath,String fileName,String remotePath) throws Exception{ ScpUtil scpUtil = new ScpUtil(); try { if(file==null) throw new FileNotFoundException("文件未找到"); File newFile = new File(basePath + fileName); FileUtil.copyValidFiles(file, newFile); file.delete(); Map<String, String> remoteMap = PropertiesUtil.getParameterMap(160225); String remoteIp = remoteMap.get("ip"); String remoteUsername = remoteMap.get("username"); String remotePassword = remoteMap.get("password"); Integer remotePort = Integer.parseInt(remoteMap.get("port")); int connectResult = scpUtil.connectServer(remoteIp, remotePort, remoteUsername, remotePassword); if(connectResult != 200) { throw new Exception("连接远程服务器失败"); } int uploadResult = scpUtil.uploadFile(basePath, fileName, remotePath, false); if(uploadResult != 200){ throw new Exception("文件上传失败"); } newFile.delete(); } catch (FileNotFoundException e) { throw new Exception("文件未找到", e); } catch (Exception e) { throw new Exception(e.getMessage(), e); } finally { if(scpUtil != null) scpUtil.closeServer(); } } }