当前位置:首页 » 文件管理 » 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());
}
}
}
热点内容
商汤科技存储负责人 发布:2025-07-15 01:24:21 浏览:252
文件夹如何批量替换文件名 发布:2025-07-15 01:19:15 浏览:68
ftp上传网页 发布:2025-07-15 01:13:09 浏览:182
音乐文件夹图标 发布:2025-07-15 01:03:41 浏览:495
安卓机怎么反向充电 发布:2025-07-15 01:03:40 浏览:501
电脑使用华为云服务器 发布:2025-07-15 00:48:10 浏览:534
中考应该如何排解压力 发布:2025-07-15 00:17:54 浏览:363
安卓第三方应用软件是什么 发布:2025-07-15 00:12:06 浏览:149
程序业务配置存储 发布:2025-07-14 23:52:16 浏览:685
csdn编程挑战 发布:2025-07-14 23:52:08 浏览:791