程序升級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();}}}
新聞熱點
疑難解答