生活随笔
收集整理的這篇文章主要介紹了
Apache FTPClient操作文件上传下载及公共类
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
我們?cè)陧?xiàng)目中可能需要使用ftp進(jìn)行文件的上傳、下載、獲取服務(wù)器目錄信息等相關(guān)操作,我們可以使用apache的FTPClient進(jìn)行相關(guān)的操作,下面把相關(guān)公共方法與大家交流分享,每個(gè)方法前都有詳細(xì)的注釋進(jìn)行講解,不過(guò)在進(jìn)行ftp測(cè)試的時(shí)候,我們需要配置一個(gè)ftp的服務(wù)器,進(jìn)行文件的上傳和下載,大家可以在網(wǎng)上找相關(guān)資料進(jìn)行設(shè)置,把環(huán)境搭建好就可以進(jìn)行我們的測(cè)試了,我們?cè)谶M(jìn)行apche ftp相關(guān)操作的時(shí)候,需要一個(gè)jar包支持,commons-net.jar,大家可以在我的資源庫(kù)中進(jìn)行免費(fèi)下載:
http://download.csdn.net/detail/harderxin/7053691
編寫(xiě)我們的FTPCongfig類,用于將登陸信息封裝為我們實(shí)體類:
package com.xin.test; /** * ftp登陸配置信息 * @author HarderXin * */ public class FtpConfig { //服務(wù)器地址名稱 private String server; //端口號(hào) private int port; //用戶名稱 private String username; //密碼 private String password; //工作目錄 private String location; public String getServer() { return server; } public void setServer(String server) { this.server = server; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
2、編寫(xiě)我們的FtpUtil進(jìn)行ftp相關(guān)操作:
package com.xin.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPFileFilter; public class FtpUtil { private FTPClient ftpClient; public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE; public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE; /** * 利用FtpConfig進(jìn)行服務(wù)器連接 * @param ftpConfig 參數(shù)配置Bean類 * @throws SocketException * @throws IOException */ public void connectServer(FtpConfig ftpConfig) throws SocketException, IOException { String server = ftpConfig.getServer(); int port = ftpConfig.getPort(); String user = ftpConfig.getUsername(); String password = ftpConfig.getPassword(); String location = ftpConfig.getLocation(); connectServer(server, port, user, password, location); } /** * 使用詳細(xì)信息進(jìn)行服務(wù)器連接 * @param server:服務(wù)器地址名稱 * @param port:端口號(hào) * @param user:用戶名 * @param password:用戶密碼 * @param path:轉(zhuǎn)移到FTP服務(wù)器目錄 * @throws SocketException * @throws IOException */ public void connectServer(String server, int port, String user, String password, String path) throws SocketException, IOException { ftpClient = new FTPClient(); ftpClient.connect(server, port); System.out.println("Connected to " + server + "."); //連接成功后的回應(yīng)碼 System.out.println(ftpClient.getReplyCode()); ftpClient.login(user, password); if (path!=null&&path.length() != 0) { ftpClient.changeWorkingDirectory(path); } ftpClient.setBufferSize(1024);//設(shè)置上傳緩存大小 ftpClient.setControlEncoding("UTF-8");//設(shè)置編碼 ftpClient.setFileType(BINARY_FILE_TYPE);//設(shè)置文件類型 } /** * 設(shè)置傳輸文件類型:FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE * 二進(jìn)制文件或文本文件 * @param fileType * @throws IOException */ public void setFileType(int fileType) throws IOException { ftpClient.setFileType(fileType); } /** * 關(guān)閉連接 * @throws IOException */ public void closeServer() throws IOException { if (ftpClient!=null&&ftpClient.isConnected()) { ftpClient.logout();//退出FTP服務(wù)器 ftpClient.disconnect();//關(guān)閉FTP連接 } } /** * 轉(zhuǎn)移到FTP服務(wù)器工作目錄 * @param path * @return * @throws IOException */ public boolean changeDirectory(String path) throws IOException { return ftpClient.changeWorkingDirectory(path); } /** * 在服務(wù)器上創(chuàng)建目錄 * @param pathName * @return * @throws IOException */ public boolean createDirectory(String pathName) throws IOException { return ftpClient.makeDirectory(pathName); } /** * 在服務(wù)器上刪除目錄 * @param path * @return * @throws IOException */ public boolean removeDirectory(String path) throws IOException { return ftpClient.removeDirectory(path); } /** * 刪除所有文件和目錄 * @param path * @param isAll true:刪除所有文件和目錄 * @return * @throws IOException */ public boolean removeDirectory(String path, boolean isAll) throws IOException { if (!isAll) { return removeDirectory(path); } FTPFile[] ftpFileArr = ftpClient.listFiles(path); if (ftpFileArr == null || ftpFileArr.length == 0) { return removeDirectory(path); } // for (FTPFile ftpFile : ftpFileArr) { String name = ftpFile.getName(); if (ftpFile.isDirectory()) { System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]"); removeDirectory(path + "/" + name, true); } else if (ftpFile.isFile()) { System.out.println("* [sF]Delete file ["+path + "/" + name+"]"); deleteFile(path + "/" + name); } else if (ftpFile.isSymbolicLink()) { } else if (ftpFile.isUnknown()) { } } return ftpClient.removeDirectory(path); } /** * 檢查目錄在服務(wù)器上是否存在 true:存在 false:不存在 * @param path * @return * @throws IOException */ public boolean existDirectory(String path) throws IOException { boolean flag = false; FTPFile[] ftpFileArr = ftpClient.listFiles(path); for (FTPFile ftpFile : ftpFileArr) { if (ftpFile.isDirectory() && ftpFile.getName().equalsIgnoreCase(path)) { flag = true; break; } } return flag; } /** * 得到文件列表,listFiles返回包含目錄和文件,它返回的是一個(gè)FTPFile數(shù)組 * listNames():只包含目錄的字符串?dāng)?shù)組 * String[] fileNameArr = ftpClient.listNames(path); * @param path:服務(wù)器上的文件目錄:/DF4 */ public List<String> getFileList(String path) throws IOException { FTPFile[] ftpFiles= ftpClient.listFiles(path); //通過(guò)FTPFileFilter遍歷只獲得文件 /* FTPFile[] ftpFiles2= ftpClient.listFiles(path,new FTPFileFilter() { @Override public boolean accept(FTPFile ftpFile) { return ftpFile.isFile(); } }); */ List<String> retList = new ArrayList<String>(); if (ftpFiles == null || ftpFiles.length == 0) { return retList; } for (FTPFile ftpFile : ftpFiles) { if (ftpFile.isFile()) { retList.add(ftpFile.getName()); } } return retList; } /** * 刪除服務(wù)器上的文件 * @param pathName * @return * @throws IOException */ public boolean deleteFile(String pathName) throws IOException { return ftpClient.deleteFile(pathName); } /** * 上傳文件到ftp服務(wù)器 * 在進(jìn)行上傳和下載文件的時(shí)候,設(shè)置文件的類型最好是: * ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) * localFilePath:本地文件路徑和名稱 * remoteFileName:服務(wù)器文件名稱 */ public boolean uploadFile(String localFilePath, String remoteFileName) throws IOException { boolean flag = false; InputStream iStream = null; try { iStream = new FileInputStream(localFilePath); //我們可以使用BufferedInputStream進(jìn)行封裝 //BufferedInputStream bis=new BufferedInputStream(iStream); //flag = ftpClient.storeFile(remoteFileName, bis); flag = ftpClient.storeFile(remoteFileName, iStream); } catch (IOException e) { flag = false; return flag; } finally { if (iStream != null) { iStream.close(); } } return flag; } /** * 上傳文件到ftp服務(wù)器,上傳新的文件名稱和原名稱一樣 * @param fileName:文件名稱 * @return * @throws IOException */ public boolean uploadFile(String fileName) throws IOException { return uploadFile(fileName, fileName); } /** * 上傳文件到ftp服務(wù)器 * @param iStream 輸入流 * @param newName 新文件名稱 * @return * @throws IOException */ public boolean uploadFile(InputStream iStream, String newName) throws IOException { boolean flag = false; try { flag = ftpClient.storeFile(newName, iStream); } catch (IOException e) { flag = false; return flag; } finally { if (iStream != null) { iStream.close(); } } return flag; } /** * 從ftp服務(wù)器上下載文件到本地 * @param remoteFileName:ftp服務(wù)器上文件名稱 * @param localFileName:本地文件名稱 * @return * @throws IOException */ public boolean download(String remoteFileName, String localFileName) throws IOException { boolean flag = false; File outfile = new File(localFileName); OutputStream oStream = null; try { oStream = new FileOutputStream(outfile); //我們可以使用BufferedOutputStream進(jìn)行封裝 //BufferedOutputStream bos=new BufferedOutputStream(oStream); //flag = ftpClient.retrieveFile(remoteFileName, bos); flag = ftpClient.retrieveFile(remoteFileName, oStream); } catch (IOException e) { flag = false; return flag; } finally { oStream.close(); } return flag; } /** * 從ftp服務(wù)器上下載文件到本地 * @param sourceFileName:服務(wù)器資源文件名稱 * @return InputStream 輸入流 * @throws IOException */ public InputStream downFile(String sourceFileName) throws IOException { return ftpClient.retrieveFileStream(sourceFileName); } }
3、編寫(xiě)我們的測(cè)試類:
public static void main(String args[]) throws Exception{ //testUpload(); //testDownload(); FtpUtil ftpUtil=new FtpUtil(); ftpUtil.connectServer("192.168.1.254", FTPClient.DEFAULT_PORT, "image", "123456", null); //獲得ftp服務(wù)器上目錄名稱為DF4下的所有文件名稱 List<String> list=ftpUtil.getFileList("/DF4"); System.out.println("文件名稱列表為:"+list); //上傳本地D盤(pán)文件aaa.txt到服務(wù)器,服務(wù)器上名稱為bbb.txt ftpUtil.uploadFile("d:" + File.separator + "aaa.txt", "eee.txt"); //從服務(wù)器上下載文件bbb.txt到本地d盤(pán)名稱為ccc.txt ftpUtil.download("eee.txt", "d:" + File.separator + "fff.txt"); //刪除ftp服務(wù)器上文件:bbb.txt //ftpUtil.deleteFile("bbb.txt"); }
有類似需求的時(shí)候,大家可以使用上面的代碼進(jìn)行參考,供交流學(xué)習(xí)!!
轉(zhuǎn)載于:https://blog.51cto.com/8786457/1389845
總結(jié)
以上是生活随笔為你收集整理的Apache FTPClient操作文件上传下载及公共类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。