1. java 实现ftp上传下载,windows下和linux下游何区别
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());
}
}
}
2. FTPClient.storeFile报连接超时。但是已经能login,而且建立了文件夹了。再调storeFile时报错。
我遇到过这个问题,改成在建立连接之前设置被动模式,就可以上传了。
3. FTP协议有两种工作方式是什么
Ftp协议的两种工作模式:主动模式active和被动模式passive
FTP 是一种数据传输协议 (File Transfer Protocol),它的连接模式有两种: 主动模式( active )和被动模式( passive )。
以下说明FTP的连接是怎样建立的:
在 active 模式下 (一般预设的模式):
FTP client 开启一个随机选择的TCP port 呼叫 FTP server 的 port 21请求建立连接。当完成 Three-Way Handshake 之后,连接就成功建立,但这仅是命令通道的建立。
当两端需要传送数据资料的时候,client 透过命令通道用一个 port command 告诉 server ,client可以用另一个TCP port 做数据通道。
然后 server 用 port 20 和刚才client 所告知的 TCP port 建立数据连接。注意:连接方向是从server 到 client 的,TCP 分组中会有一个 SYN flag。
然后 client 会返回一个带 ACK flag的确认分组,并完成另一次的 Three-Way Handshake 过程。这时候,数据连接才能成功建立。开始数据传送。
在 passive 模式下:
FTP client 开启一个随机选择的TCP port 呼叫 FTP server 的 port 21请求建立连接,完成命令通道的建立。
当两端需要传送数据的时候,client 通过命令通道发送一个 PASV command 给server,要求进入 passive 传输模式。
然后 server 像上述的正常模式之第 2 步骤那样,挑一个TCP port ,并用命令通道告诉 client。
然后 client 用另一个TCP port 呼叫刚才 server 告知的 TCP port 来建立数据通道。此时分组中带有 SYN flag。
server 确认后回送一个 ACK 分组。并完成所有握手过程、成功建立数据通道。
开始数据传送。 在实际使用中, active mode 用来登入一些架设在主机上没有安装防火墙的 FTP server,或是架设在 client side 的 FTP server! Passive mode (简称 PASV)用来登陆一些架设于防火墙保护下而又是开设于主机上的 FTP server!
4. 关于FTP 映射的问题,涉及主动,被动模式
如果是私网client访问公网ftp server,在主动模式下,需要防火墙/路由器开启ALG(application layer gateway)功能,功能开启后路由器/防火墙会从ftp控制报文中提取通讯端口信息,然后事先在防火墙/路由器将通讯端口映射。
你所说的情况是ftp server在私网,不知道情况是不是类似。
5. java里使用ftpClient的被动方式访问ftp服务器读取一系列文件夹,只有第一个内容能读到,其他读不到
你basePath应该有问题,basePath应该指向要删除目录的上一级目录.
6. ubuntu和centos,centos上用vsftp搭建FTP服务器,windows上用FileZilla Client主被动模式都可以正常访问
将你的FTP软件的工作模式设置为 pasv模式 就OK了 软件不同设置方法不同
(1)IE:工具 -> Internet选项 -> 高级 -> “使用被动FTP”(需要IE6.0以上才支持)。
(2)CuteFTP:Edit -> Setting -> Connection -> Firewall -> “PASV Mode” 或File -> Site Manager,在左边选中站点 -> Edit -> “Use PASV mode” 。
(3)FlashGet:工具 -> 选项 -> 代理服务器 -> 直接连接 -> 编辑 -> “PASV模式”。
(4)FlashFXP:选项 -> 参数选择 -> 代理/防火墙/标识 -> “使用被动模式” 或 站点管理 -> 对应站点 -> 选项 -> “使用被动模式”或快速连接 -> 切换 -> “使用被动模式”。
在cmd里面:
如果需要切换到PORT模式:quote PORT;
同样,如果需要PASV模式:quote PASV即可.
7. ftp的路径怎么设置
你先使用cd 命令切换到你想下载的目录下,如:
cmd
cd d:\wenjian
之后在使用ftp命令。就可以了
8. java的ftp用匿名如何登陆啊...下载中文乱码......
首先,匿名不是null,匿名是anonymous,密码可以为空
乱码
ftpConfig.setServerLanguageCode("zh");
ftpClient.setControlEncoding("GBK");
如果还为乱码,则加上转码
new String(names[i].getBytes("GBK"),"ISO-8859-1")
9. 为什么ftp用FileZilla可以正常上传图片,使用java代码走到client.storefile();就
既然你可以用filezilla连接并实现上传, 说明服务器是没有问题的, 那么就要检查一下你的windows是否有问题了. 首先看一下windows的防火墙是不是开了, 如果打开了, 关闭一下, 再尝试一下上传功能, 看能够成功. 如果不行, 看一下你的ftpclient相关的jar包版本和jdk版本是否匹配, 这里也可能出问题.
希望能够帮到你.