當前位置:首頁 » 文件管理 » javaftp文件是否存在

javaftp文件是否存在

發布時間: 2022-09-26 01:26:41

A. java如何測試連接ftp是否通

java測試連接ftp是否連通可以使用判斷是否有異常來決定,實例如下:

/**
*connectServer
*連接ftp伺服器
*@throwsjava.io.IOException
*@parampath文件夾,空代表根目錄
*@parampassword密碼
*@paramuser登陸用戶
*@paramserver伺服器地址
*/
publicvoidconnectServer(Stringserver,Stringuser,Stringpassword,Stringpath)
throwsIOException
{
//server:FTP伺服器的IP地址;user:登錄FTP伺服器的用戶名
//password:登錄FTP伺服器的用戶名的口令;path:FTP伺服器上的路徑
ftpClient=newFtpClient();
ftpClient.openServer(server);
ftpClient.login(user,password);
//path是ftp服務下主目錄的子目錄
if(path.length()!=0)ftpClient.cd(path);
//用2進制上傳、下載
ftpClient.binary();
}

/**
*upload
*上傳文件
*@throwsjava.lang.Exception
*@return-1文件不存在
*-2文件內容為空
*>0成功上傳,返迴文件的大小
*@paramnewname上傳後的新文件名
*@paramfilename上傳的文件
*/
publiclongupload(Stringfilename,Stringnewname)throwsException
{
longresult=0;
TelnetOutputStreamos=null;
FileInputStreamis=null;
try{
java.io.Filefile_in=newjava.io.File(filename);
if(!file_in.exists())return-1;
if(file_in.length()==0)return-2;
os=ftpClient.put(newname);
result=file_in.length();
is=newFileInputStream(file_in);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
}
}finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*upload
*@throwsjava.lang.Exception
*@return
*@paramfilename
*/
publiclongupload(Stringfilename)
throwsException
{
Stringnewname="";
if(filename.indexOf("/")>-1)
{
newname=filename.substring(filename.lastIndexOf("/")+1);
}else
{
newname=filename;
}
returnupload(filename,newname);
}

/**
*download
*從ftp下載文件到本地
*@throwsjava.lang.Exception
*@return
*@paramnewfilename本地生成的文件名
*@paramfilename伺服器上的文件名
*/
publiclongdownload(Stringfilename,Stringnewfilename)
throwsException
{
longresult=0;
TelnetInputStreamis=null;
FileOutputStreamos=null;
try
{
is=ftpClient.get(filename);
java.io.Fileoutfile=newjava.io.File(newfilename);
os=newFileOutputStream(outfile);
byte[]bytes=newbyte[1024];
intc;
while((c=is.read(bytes))!=-1){
os.write(bytes,0,c);
result=result+c;
}
}catch(IOExceptione)
{
e.printStackTrace();
}
finally{
if(is!=null){
is.close();
}
if(os!=null){
os.close();
}
}
returnresult;
}
/**
*取得某個目錄下的所有文件列表
*
*/
publicListgetFileList(Stringpath)
{
Listlist=newArrayList();
try
{
DataInputStreamdis=newDataInputStream(ftpClient.nameList(path));
Stringfilename="";
while((filename=dis.readLine())!=null)
{
list.add(filename);
}

}catch(Exceptione)
{
e.printStackTrace();
}
returnlist;
}

/**
*closeServer
*斷開與ftp伺服器的鏈接
*@throwsjava.io.IOException
*/
publicvoidcloseServer()
throwsIOException
{
try
{
if(ftpClient!=null)
{
ftpClient.closeServer();
}
}catch(IOExceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args)throwsException
{
FtpUtilftp=newFtpUtil();
try{
//連接ftp伺服器
ftp.connectServer("10.163.7.15","cxl","1","info2");
/**上傳文件到info2文件夾下*/
System.out.println("filesize:"+ftp.upload("f:/download/Install.exe")+"位元組");
/**取得info2文件夾下的所有文件列表,並下載到E盤下*/
Listlist=ftp.getFileList(".");
for(inti=0;i<list.size();i++)
{
Stringfilename=(String)list.get(i);
System.out.println(filename);
ftp.download(filename,"E:/"+filename);
}
}catch(Exceptione){
///
}finally
{
ftp.closeServer();
}
}
}

B. java 如何判斷ftp文件存不存在

是可以這樣判斷
但是 你要注意的是 你的程序有可能和FTP不再同一台伺服器上
所以 你要多做一些工作 你先要根據獲取FTP的IP
根據這個IP的FTP目錄 在進行判斷

C. java 判斷FTP當前目錄下的文件是普通文件還是目錄

private boolean checkFileName(downFileName) {
try {
ftp.cd(downFileName); //不是目錄時,將報錯
ftp.cd(".."); // 回到原來的目錄
return true;
}catch(Exception e) {
return false;
}
}

D. java 在ftp上的所有文件查詢文件是否存在

packagetest;
importjava.io.DataInputStream;
importsun.net.ftp.FtpClient;
publicclassFtpDown1{
publicstaticvoidmain(Stringargs[])throwsException{
Stringhost="ip地址";
Stringpath="";
Stringusername="用戶名";
Stringpassword="密碼";
FtpClientclient=newFtpClient(host);
client.login(username,password);
client.binary();
client.cd("/目錄名稱");//如果是根目錄下直接寫個/就行了,或者不寫
DataInputStreamdis=newDataInputStream(client.nameList("test_*.xml"));
intreadCount;
Strings="";
while((s=dis.readLine())!=null){
//在此處判斷是否存在對應的文件
System.out.println("Getting:"+s);
}
}
}

E. java 怎麼查看ftp目錄是否存在

ftpClient.makeDirectory(目錄地址); 返回結果true或false
返回true證明創建成功,即在執行創建命令前ftp上不存在此目錄
返回false證明創建失敗,即ftp上已存在此目錄

F. JAVA當中如何在FTP上查找文件或目錄是否存在

我覺得用file的exists就可以
File f=new File("file url");
if(f.exists()){
System.out.println("exists");
}
else{
System.out.println("not exist");
}

G. 你好: 我也在做這個E語言,我們的伺服器是linux的,用Java去查找FTP上的指定E文件是否存在,可是取過來的

我的情況是把文件上傳到ftp伺服器時,發現ftp伺服器文件名稱亂碼,所以我就對文件名編碼,
當然你可以根據自己的情況寫轉換方法:
boolean b = ftpClient.storeFile(GBKToiso8859(filename), input);

/**
* 轉碼[GBK -> iso-8859-1] 不同的平台需要不同的轉碼
*
* @param obj
* @return
*/
private String GBKToiso8859(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
} catch (Exception e) {
return "";
}
}

H. java開發ftp客戶端對伺服器文件狀態如何識別

我們當時是這樣處理的:

上傳一個文件,比如名字為:aaa.rar
當文件上傳完的時候就會上傳一個aaa.fin的空文件做標識,表明這個文件上傳成功。

下載的時候首先檢查aaa.fin是否存在。然後下載!

建議你在文件目錄下放一個list.xml(存放當前上傳成功的文件名,下載前在裡面檢索它是否存在)

I. 請問一下,java中有沒直接判斷ftp上文件夾下是否存在某文件的方法通過遍歷文件夾的方式判斷太耗內存了

第一個種方法 :
org.apache.commons.net.ftp.* 看這個目錄下是否有你要的方法
第二種方法:

package com.soft4j.log4j;

import java.io.IOException;

import sun.net.ftp.FtpClient;

public class FtpTest
{
static String middle_ftpServer = "10.103.2.250";
static String middle_user = "ora9iftp";
static String middle_password = "ftp";
static String middle_dir = "/image/NWKPHOTO/Middle/2009/3";

public static void main(String[] args)
{
FtpClient ftpClient = new FtpClient();
try
{
ftpClient.openServer(middle_ftpServer);
ftpClient.login(middle_user, middle_password);
FtpTest ft = new FtpTest();
ft.isDirExist(ftpClient, middle_dir);
} catch (IOException e)
{
e.printStackTrace();
}

}

/** 判斷Ftp目錄是否存在,如果不存在則創建目錄 */
public void isDirExist(FtpClient ftpClient, String dir)
{
try
{
ftpClient.cd(dir); //想不到什麼好辦法來判斷目錄是否存在,只能用異常了(比較笨).請知道的告訴我一聲`
} catch (IOException e1)
{
ftpClient.sendServer("MKD " + dir + "\r\n");
try
{
ftpClient.readServerResponse();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}

J. java 怎麼從ftp獲取文件路徑

拿去用吧。

packagecom.weixin.util;

importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.RandomAccessFile;

importorg.apache.commons.net.PrintCommandListener;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;

importcom.weixin.constant.DownloadStatus;
importcom.weixin.constant.UploadStatus;

/**
*支持斷點續傳的FTP實用類
*@version0.1實現基本斷點上傳下載
*@version0.2實現上傳下載進度匯報
*@version0.3實現中文目錄創建及中文文件創建,添加對於中文的支持
*/
publicclassContinueFTP{
publicFTPClientftpClient=newFTPClient();

publicContinueFTP(){
//設置將過程中使用到的命令輸出到控制台
this.ftpClient.addProtocolCommandListener(newPrintCommandListener(newPrintWriter(System.out)));
}

/**
*連接到FTP伺服器
*@paramhostname主機名
*@paramport埠
*@paramusername用戶名
*@parampassword密碼
*@return是否連接成功
*@throwsIOException
*/
publicbooleanconnect(Stringhostname,intport,Stringusername,Stringpassword)throwsIOException{
ftpClient.connect(hostname,port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username,password)){
returntrue;
}
}
disconnect();
returnfalse;
}

/**
*從FTP伺服器上下載文件,支持斷點續傳,上傳百分比匯報
*@paramremote遠程文件路徑
*@paramlocal本地文件路徑
*@return上傳的狀態
*@throwsIOException
*/
publicDownloadStatusdownload(Stringremote,Stringlocal)throwsIOException{
//設置被動模式
ftpClient.enterLocalPassiveMode();
//設置以二進制方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatusresult;

//檢查遠程文件是否存在
FTPFile[]files=ftpClient.listFiles(newString(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length!=1){
System.out.println("遠程文件不存在");
returnDownloadStatus.Remote_File_Noexist;
}

longlRemoteSize=files[0].getSize();
Filef=newFile(local);
//本地存在文件,進行斷點下載
if(f.exists()){
longlocalSize=f.length();
//判斷本地文件大小是否大於遠程文件大小
if(localSize>=lRemoteSize){
System.out.println("本地文件大於遠程文件,下載中止");
returnDownloadStatus.Local_Bigger_Remote;
}

//進行斷點續傳,並記錄狀態
FileOutputStreamout=newFileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=localSize/step;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下載進度:"+process);
//TODO更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
booleanisDo=ftpClient.completePendingCommand();
if(isDo){
result=DownloadStatus.Download_From_Break_Success;
}else{
result=DownloadStatus.Download_From_Break_Failed;
}
}else{
OutputStreamout=newFileOutputStream(f);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=0;
longlocalSize=0L;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下載進度:"+process);
//TODO更新文件下載進度,值存放在process變數中
}
}
in.close();
out.close();
booleanupNewStatus=ftpClient.completePendingCommand();
if(upNewStatus){
result=DownloadStatus.Download_New_Success;
}else{
result=DownloadStatus.Download_New_Failed;
}
}
returnresult;
}

/**
*上傳文件到FTP伺服器,支持斷點續傳
*@paramlocal本地文件名稱,絕對路徑
*@paramremote遠程文件路徑,使用/home/directory1/subdirectory/file.ext按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
*@return上傳結果
*@throwsIOException
*/
publicUploadStatusupload(Stringlocal,Stringremote)throwsIOException{
//設置PassiveMode傳輸
ftpClient.enterLocalPassiveMode();
//設置以二進制流的方式傳輸
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatusresult;
//對遠程目錄的處理
StringremoteFileName=remote;
if(remote.contains("/")){
remoteFileName=remote.substring(remote.lastIndexOf("/")+1);
//創建伺服器遠程目錄結構,創建失敗直接返回
if(CreateDirecroty(remote,ftpClient)==UploadStatus.Create_Directory_Fail){
returnUploadStatus.Create_Directory_Fail;
}
}

//檢查遠程是否存在文件
FTPFile[]files=ftpClient.listFiles(newString(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length==1){
longremoteSize=files[0].getSize();
Filef=newFile(local);
longlocalSize=f.length();
if(remoteSize==localSize){
returnUploadStatus.File_Exits;
}elseif(remoteSize>localSize){
returnUploadStatus.Remote_Bigger_Local;
}

//嘗試移動文件內讀取指針,實現斷點續傳
result=uploadFile(remoteFileName,f,ftpClient,remoteSize);

//如果斷點續傳沒有成功,則刪除伺服器上文件,重新上傳
if(result==UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
returnUploadStatus.Delete_Remote_Faild;
}
result=uploadFile(remoteFileName,f,ftpClient,0);
}
}else{
result=uploadFile(remoteFileName,newFile(local),ftpClient,0);
}
returnresult;
}
/**
*斷開與遠程伺服器的連接
*@throwsIOException
*/
publicvoiddisconnect()throwsIOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}

/**
*遞歸創建遠程伺服器目錄
*@paramremote遠程伺服器文件絕對路徑
*@paramftpClientFTPClient對象
*@return目錄創建是否成功
*@throwsIOException
*/
(Stringremote,FTPClientftpClient)throwsIOException{
UploadStatusstatus=UploadStatus.Create_Directory_Success;
Stringdirectory=remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(newString(directory.getBytes("GBK"),"iso-8859-1"))){
//如果遠程目錄不存在,則遞歸創建遠程伺服器目錄
intstart=0;
intend=0;
if(directory.startsWith("/")){
start=1;
}else{
start=0;
}
end=directory.indexOf("/",start);
while(true){
StringsubDirectory=newString(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else{
System.out.println("創建目錄失敗");
returnUploadStatus.Create_Directory_Fail;
}
}

start=end+1;
end=directory.indexOf("/",start);

//檢查所有目錄是否創建完畢
if(end<=start){
break;
}
}
}
returnstatus;
}

/**
*上傳文件到伺服器,新上傳和斷點續傳
*@paramremoteFile遠程文件名,在上傳之前已經將伺服器工作目錄做了改變
*@paramlocalFile本地文件File句柄,絕對路徑
*@paramprocessStep需要顯示的處理進度步進值
*@paramftpClientFTPClient引用
*@return
*@throwsIOException
*/
publicUploadStatusuploadFile(StringremoteFile,FilelocalFile,FTPClientftpClient,longremoteSize)throwsIOException{
UploadStatusstatus;
//顯示進度的上傳
longstep=localFile.length()/100;
longprocess=0;
longlocalreadbytes=0L;
RandomAccessFileraf=newRandomAccessFile(localFile,"r");
OutputStreamout=ftpClient.appendFileStream(newString(remoteFile.getBytes("GBK"),"iso-8859-1"));
//斷點續傳
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process=remoteSize/step;
raf.seek(remoteSize);
localreadbytes=remoteSize;
}
byte[]bytes=newbyte[1024];
intc;
while((c=raf.read(bytes))!=-1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes/step!=process){
process=localreadbytes/step;
System.out.println("上傳進度:"+process);
//TODO匯報上傳狀態
}
}
out.flush();
raf.close();
out.close();
booleanresult=ftpClient.completePendingCommand();
if(remoteSize>0){
status=result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else{
status=result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
returnstatus;
}

publicstaticvoidmain(String[]args){
ContinueFTPmyFtp=newContinueFTP();
try{
System.err.println(myFtp.connect("10.10.6.236",21,"5","jieyan"));
// myFtp.ftpClient.makeDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(newString("愛你等於愛自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\yw.flv","/yw.flv",5));
// System.out.println(myFtp.upload("E:\愛你等於愛自己.mp4","/愛你等於愛自己.mp4"));
//System.out.println(myFtp.download("/愛你等於愛自己.mp4","E:\愛你等於愛自己.mp4"));
myFtp.disconnect();
}catch(IOExceptione){
System.out.println("連接FTP出錯:"+e.getMessage());
}
}
}
熱點內容
怎麼把自家電腦變成伺服器 發布:2024-04-17 01:14:58 瀏覽:160
有哪些高配置的游戲手機 發布:2024-04-17 01:09:11 瀏覽:436
交易系統編程 發布:2024-04-17 00:09:50 瀏覽:699
編程思想pdf下載 發布:2024-04-16 23:56:26 瀏覽:183
資料庫網格計算 發布:2024-04-16 23:28:13 瀏覽:22
電波蘿莉醬解壓 發布:2024-04-16 23:26:59 瀏覽:547
平板訪問密碼是什麼時候設置的 發布:2024-04-16 23:15:52 瀏覽:178
pyinstaller如何自定義配置打包 發布:2024-04-16 22:51:54 瀏覽:199
怎麼設置建行登陸密碼 發布:2024-04-16 22:49:58 瀏覽:58
大型激光編程 發布:2024-04-16 22:41:04 瀏覽:535