java查询ftp路径下所有文件名字
生活随笔
收集整理的這篇文章主要介紹了
java查询ftp路径下所有文件名字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.company.project.utils;import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;import java.io.IOException;
import java.util.ArrayList;/*** 列出FTP服務器上指定目錄下面的所有文件*/
public class FTPListAllFiles {public FTPClient ftp;public ArrayList<String> arFiles;private static final String FAR_SERVER_URL = "10.*.*.4";private static final int SERVER_PORT = 21;private static final String SERVER_USER = "ftpuser";private static final String SERVER_PWD = "123456";private static final String path = "/data/ftp/";private static final String downloadPath = "";/*** 登陸FTP服務器** @param host FTPServer IP地址* @param port FTPServer 端口* @param username FTPServer 登陸用戶名* @param password FTPServer 登陸密碼* @return 是否登錄成功* @throws IOException*/public boolean login(String host, int port, String username, String password) throws IOException {ftp = new FTPClient();//設置超時ftp.setConnectTimeout(60 * 60 * 1000);//設置編碼ftp.setControlEncoding("UTF-8");this.ftp.connect(host, port);if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {if (this.ftp.login(username, password)) {this.ftp.setControlEncoding("GBK");return true;}}if (this.ftp.isConnected()) {this.ftp.disconnect();}return false;}/*** 關閉數據鏈接** @throws IOException*/public void disConnection() throws IOException {if (this.ftp.isConnected()) {this.ftp.disconnect();}}/*** 遞歸遍歷出目錄下面所有文件** @param pathName 需要遍歷的目錄,必須以"/"開始和結束* @throws IOException*/public String List(String pathName) throws IOException {StringBuffer filename = new StringBuffer();if (pathName.startsWith("/") && pathName.endsWith("/")) {String directory = pathName;
//更換目錄到當前目錄this.ftp.changeWorkingDirectory(directory);ftp.enterLocalPassiveMode(); //開啟被動模式,跟端口是否開放有關,更多詳情請百度FTPFile[] files = this.ftp.listFiles();if (files != null) {for (int i = 0; i < files.length; i++) {if (files[i].isFile()) {String n = new String(files[i].getName().getBytes("gbk"), "utf-8");if (i == files.length - 1) {filename.append(n );} else {filename.append(n + ",");}}}}}return filename.toString();}//獲取指定文件夾內的文件名稱public static String getFilenames() {String names = "";FTPListAllFiles f = new FTPListAllFiles();try {if (f.login(FAR_SERVER_URL, SERVER_PORT, SERVER_USER, SERVER_PWD)) {names = f.List(path);}} catch (IOException e) {e.printStackTrace();} finally {try {f.disConnection();} catch (IOException e) {e.printStackTrace();}}return names;}//測試public static void main(String[] args) throws IOException {System.out.println(getFilenames());}
}
加了個注釋:
ftp.enterLocalPassiveMode(); //開啟被動模式,跟端口是否開放有關,更多詳情請百度總結
以上是生活随笔為你收集整理的java查询ftp路径下所有文件名字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: idea 右键没有run
- 下一篇: abcd\110的字节数、字符长度以及字