當前位置:首頁 » 文件管理 » ftpjava文件列表

ftpjava文件列表

發布時間: 2022-09-05 02:23:40

㈠ 用java獲取ftp文件列表

學習一下ftp協議,然後用socket來模擬就可以了

㈡ 用java怎麼獲取ftp上的文件

public class FtpClientUtil {
FtpClient ftpClient;
private String server;
private int port;
private String userName;
private String userPassword;

public FtpClientUtil(String server,int port,String userName,String userPassword)
{
this.server=server;
this.port=port;
this.userName=userName;
this.userPassword=userPassword;
}
/**
* 鏈接到伺服器
* @return
*/
public boolean open()
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
return true;
try
{
ftpClient= new FtpClient();
ftpClient.openServer(server,port);
ftpClient.login(userName, userPassword);
ftpClient.binary();
return true;
}
catch(Exception e)
{
e.printStackTrace();
ftpClient=null;
return false;
}
}

public boolean cd(String dir){
boolean f = false;
try {
ftpClient.cd(dir);
} catch (IOException e) {
Logs.error(e.toString());
return f;
}
return true;
}

/**
* 上傳文件到FTP伺服器
* @param localPathAndFileName 本地文件目錄和文件名
* @param ftpFileName 上傳後的文件名
* @param ftpDirectory FTP目錄如:/path1/pathb2/,如果目錄不存在回自動創建目錄
* @throws Exception
*/
public boolean upload(String localDirectoryAndFileName,String ftpFileName,String ftpDirectory)throws Exception {
if(!open())
return false;
FileInputStream is=null;
TelnetOutputStream os=null;
try
{
char ch = ' ';
if (ftpDirectory.length() > 0)
ch = ftpDirectory.charAt(ftpDirectory.length() - 1);
for (; ch == '/' || ch == '\\'; ch = ftpDirectory.charAt(ftpDirectory.length() - 1))
ftpDirectory = ftpDirectory.substring(0, ftpDirectory.length() - 1);

int slashIndex = ftpDirectory.indexOf(47);
int backslashIndex = ftpDirectory.indexOf(92);
int index = slashIndex;
String dirall = ftpDirectory;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
String directory = "";
while (index != -1) {
if (index > 0) {
String dir = dirall.substring(0, index);
directory = directory + "/" + dir;
ftpClient.sendServer("XMKD " + directory + "\r\n");
ftpClient.readServerResponse();
}
dirall = dirall.substring(index + 1);
slashIndex = dirall.indexOf(47);
backslashIndex = dirall.indexOf(92);
index = slashIndex;
if (backslashIndex != -1 && (index == -1 || index > backslashIndex))
index = backslashIndex;
}
ftpClient.sendServer("XMKD " + ftpDirectory + "\r\n");
ftpClient.readServerResponse();

os = ftpClient.put(ftpDirectory + "/"
+ ftpFileName);
File file_in = new File(localDirectoryAndFileName);
is = new FileInputStream(file_in);
byte bytes[] = new byte[1024];
int i;
while ((i = is.read(bytes)) != -1)
os.write(bytes, 0, i);
//清理垃圾

return true;
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();
}
}
/**
* 從FTP伺服器上下載文件並返回下載文件長度
* @param ftpDirectoryAndFileName
* @param localDirectoryAndFileName
* @return
* @throws Exception
*/
public long download(String ftpDirectoryAndFileName,String localDirectoryAndFileName)throws Exception
{
long result = 0;
if(!open())
return result;
TelnetInputStream is = null;
FileOutputStream os = null;
try
{
is = ftpClient.get(ftpDirectoryAndFileName);
java.io.File outfile = new java.io.File(localDirectoryAndFileName);
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 (Exception e)
{
throw e;
}
finally
{
if (is != null)
is.close();
if (os != null)
os.close();

}
return result;
}
/**
* 返回FTP目錄下的文件列表
* @param ftpDirectory
* @return
*/
public List<String> getFileNameList(String ftpDirectory)
{
List<String> list = new ArrayList<String>();
if(!open())
return list;
try
{
DataInputStream dis = new DataInputStream(ftpClient.nameList(ftpDirectory));
String filename = "";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}
} catch (Exception e)
{
e.printStackTrace();
}
return list;
}
/**
* 刪除FTP上的文件
* @param ftpDirAndFileName
*/
public boolean deleteFile(String ftpDirAndFileName)
{
if(!open())
return false;
ftpClient.sendServer("DELE "+ftpDirAndFileName+"\r\n");
return true;
}
/**
* 刪除FTP目錄
* @param ftpDirectory
*/
public boolean deleteDirectory(String ftpDirectory)
{
if(!open())
return false;
ftpClient.sendServer("XRMD "+ftpDirectory+"\r\n");
return true;
}
/**
* 關閉鏈接
*/
public void close()
{
try
{
if(ftpClient!=null&&ftpClient.serverIsOpen())
ftpClient.closeServer();
}catch(Exception e)
{

}
}
}望採納,謝謝。

㈢ java如何獲取ftp制定目錄下所有文件集合(包括文件名稱)只要一個方法。

/**
* 取得相對於當前連接目錄的某個目錄下所有文件列表
*
* @param path
* @return
*/
public List getFileList(String path){
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while((filename = dis.readLine()) != null){
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
我從這里拷來的 你不清楚看看裡面 http://hi..com/yuanhotel/item/000b6334894d11f42784f4da
滿意就採納 謝謝

㈣ 關於JAVA FTP連接後文件列表中的中文是亂碼

需要設置文件傳輸的格式,有2中格式 1:asicc 。2:binary格式 也就是二進制格式,並且ftpClient提供了相應的方法,asicc(),barry(),你要在連接ftp的時候加上此方法,ftpClient.binary();

㈤ java 實現ftp上傳如何創建文件夾

這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

㈥ java編寫FTP伺服器軟體(非客戶端)實現一FTP伺服器,能列出/更改目錄,上下傳文件,顯示文件列表,支持NO

您找的是GFTPServer,到YufengSoftwareStudio上去下載。或在網路上查找「GFTPServer」。全Java實現的FTP伺服器,在JRE/JDK1.6環境下直接運行,傻瓜式GUI操作,非常簡便。

㈦ java怎樣獲取ftp目錄下的所有子文件名

public static void main(String[] args) {
// TODO Auto-generated method stub
// 創建File對象
File file = new File("d:\\");
// 使用遞歸方法做
dg(file);
}

private static void dg(File fl) {
// TODO Auto-generated method stub
// 創建file數組用來存儲數據
File[] filArr = fl.listFiles();
// 判斷FiLe數組不能為空
if (filArr != null) {
// 使用for遍歷
for (File f : filArr) {
// 如果是文件夾 就遞歸
if (f.isDirectory()) {
// 遞歸
dg(f);
} else if (f.isFile()) {

System.out.println(f.getAbsolutePath());
}
}
}
}

㈧ java通過ftp 連接ftp伺服器成功,怎麼list文件

1.使用的FileZillaServer開源免費軟體,安裝過後建立的本地FTP伺服器。2.使用的apache上下載FTP工具包,引用到工程目錄中。3.IDE,Eclipse,JDK6上傳和下載目錄的實現原理:對每一個層級的目錄進行判斷,是為目錄類型、還是文件類型。如果為目錄類型,採用遞歸調用方法,檢查到最底層的目錄為止結束。如果為文件類型,則調用上傳或者下載方法對文件進行上傳或者下載操作。貼出代碼:(其中有些沒有代碼,可以看看,還是很有用處的)!

㈨ 用JAVA編寫一個程序實現輸出我的電腦上建立的FTP伺服器根目錄下的所有文件名

使用File類中方法就可以實現
File[] listFiles() 返回目錄下所有的文件
File file=new File("你的ftp的根路徑");
File files[]=file.listFiles();
for(int i=0;i<files.length;i++){
System.out.println(files[i].getName() );
}
如果要獲取所有的文件和文件夾可以使用String[] list()方法。返回的是String類型的數組,其中所有文件和文件夾的相對路徑表示。

補充---
如果那樣的話那麼就需要在你的ftp伺服器上做一個socket服務端,你通過一個客戶端連接上去。然後伺服器端將獲取的文件列表數組傳遞給你,就可以了。如果想直接獲取別人的機器的文件列表是很難的,基本上是不可能的,當然是出於安全的考慮

㈩ java 怎麼遍歷ftp目錄下的所有目錄以及目錄下的文件名稱,取出文件的相對路徑

package com.hmilyld.exp;

import java.io.File;

public class ListFile {

private long[] count = new long[] { 0, 0 };

private File file;

private long[] listFile(String path) {
file = new File(path);
File[] f = file.listFiles();
for (int i = 0; i < f.length; i++) {
if (f[i].isDirectory()) {
count[0]++;
this.listFile(f[i].getPath());
} else {
count[1]++;
}
}
return count;
}

/**
* 得到指定路徑下的文件和文件夾數量
*
* @param path
* 要查看的路徑
* @return object[0]耗時(毫秒)<br>
* object[1]文件夾數量<br>
* object[2]文件數量
*/
public Object[] getFileCount(String path) {
long t = System.currentTimeMillis();
long[] count = this.listFile(path);
t = System.currentTimeMillis() - t;
Object[] o = new Object[] { Long.valueOf(t), Long.valueOf(count[0]),
Long.valueOf(count[1])};
return o;
}

public static void main(String[] args) {
ListFile l = new ListFile();
Object[] count = l.getFileCount("d:\\");
System.out.println(count[0]);
System.out.println(count[1]);
System.out.println(count[2]);
}
}

以前寫的一個獲取目錄下有多少文件和多少文件夾的代碼,
可以參考下.:)

熱點內容
網站架設多伺服器ip 發布:2024-10-12 07:42:15 瀏覽:187
linuxjdbc 發布:2024-10-12 07:38:10 瀏覽:197
pythonip正則表達式 發布:2024-10-12 07:30:24 瀏覽:177
xp怎麼認安卓手機 發布:2024-10-12 07:30:20 瀏覽:878
pythonmac開發工具 發布:2024-10-12 07:29:01 瀏覽:267
android字元數組 發布:2024-10-12 07:16:32 瀏覽:307
買安卓手機選什麼顏色 發布:2024-10-12 07:10:51 瀏覽:698
已經連接的wifi怎麼看密碼 發布:2024-10-12 07:06:07 瀏覽:59
sae上傳失敗 發布:2024-10-12 07:03:20 瀏覽:958
如何在伺服器上玩ai換臉 發布:2024-10-12 06:43:47 瀏覽:913