java实现ftp下载文件|java实现ftp文件操作的方式有哪些

㈠ java ftp下载

这个和ftp没有太大关系,只是一个普通的下载,java连接ftp服务器传输文件是需要提供ip 端口号,用户名密码 路径的,这个只是一个静态资源,用这个就可以,支持断点续传

这边用到了apachecommons-httpclient-3.1包

importjava.io.File;importjava.io.IOException;importjava.io.InputStream;importjava.io.RandomAccessFile;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.DefaultHttpClient;@SuppressWarnings("deprecation")publicclassDownloadTool{publicstaticvoidmain(String[]args)throwsClientProtocolException,IOException{Stringurl="[阳光电影].神探驾到.BD.720p.国粤双语中字.mkv";StringdownFile="d:\aaa.mkv";//本地存放路径LongnetFileLenght=getNetFileSize(url);LonglocalFileLenght=getLocalFileSize(downFile);if(localFileLenght>=netFileLenght){System.out.println("已下载完成");return;}System.out.println("netFileLenght:"+netFileLenght+"localFileLenght:"+localFileLenght);finalHttpClienthttpClient=newDefaultHttpClient();httpClient.getParams().setIntParameter("http.socket.timeout",5000);finalHttpGethttpGet=newHttpGet(url);httpGet.addHeader("Range","bytes="+localFileLenght+"-");finalHttpResponseresponse=httpClient.execute(httpGet);finalintcode=response.getStatusLine().getStatusCode();finalHttpEntityentity=response.getEntity();System.out.println(code);if(entity!=null&&code<400){Filefile=newFile(downFile);=newRandomAccessFile(file,"rw");randomAccessFile.seek(localFileLenght);InputStreaminputStream=entity.getContent();intb=0;finalbytebuffer[]=newbyte[1024];while((b=inputStream.read(buffer))!=-1){randomAccessFile.write(buffer,0,b);}randomAccessFile.close();inputStream.close();httpClient.getConnectionManager().shutdown();System.out.println("下载完成");}}(StringfileName){Filefile=newFile(fileName);returnfile.length();}(Stringurl){Longcount=-1L;finalHttpClienthttpClient=newDefaultHttpClient();httpClient.getParams().setIntParameter("http.socket.timeout",5000);finalHttpGethttpGet=newHttpGet(url);HttpResponseresponse=null;try{response=httpClient.execute(httpGet);finalintcode=response.getStatusLine().getStatusCode();finalHttpEntityentity=response.getEntity();if(entity!=null&&code==200){count=entity.getContentLength();}}catch(ClientProtocolExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}finally{httpClient.getConnectionManager().shutdown();}returncount;}}

㈡ 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());}}}

㈢ java如何实现txt下载 就是从远程FTP服务器上直接把TXT文本下载下来!

strUrl为文件地址,fileName为文件在本地的保存路径,试试吧~public static void writeFile(String strUrl, String fileName) { URL url = null; try { url = new URL(strUrl); } catch (MalformedURLException e2) { e2.printStackTrace(); } InputStream is = null; try { is = url.openStream(); } catch (IOException e1) { e1.printStackTrace(); } OutputStream os = null; try { os = new FileOutputStream( fileName); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } System.out.println("下载成功:"+strUrl); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

㈣ Java实现FTP文件上传下载遇到的问题,求助!

你好,Socket本身就有网络输入输出流的,不用创建多个Socket。如果要上传就用Socket的网络输出流。如果要下载就用Socket网络输入流获取服务器传送的数据。服务器可以获取到已连接的Socket对象,所以它也可以获取到网络输入输出流。 如果满意,请采纳,谢谢。

㈤ 如何在Java程序中实现FTP的上传下载功能

以下是这三部分的JAVA源程序: (1)显示FTP服务器上的文件 void ftpList_actionPerformed(ActionEvent e) {String server=serverEdit.getText();//输入的FTP服务器的IP地址 String user=userEdit.getText();//登录FTP服务器的用户名 String password=passwordEdit.getText();//登录FTP服务器的用户名的口令 String path=pathEdit.getText();//FTP服务器上的路径 try {FtpClient ftpClient=new FtpClient();//创建FtpClient对象 ftpClient.openServer(server);//连接FTP服务器 ftpClient.login(user, password);//登录FTP服务器 if (path.length()!=0) ftpClient.cd(path); TelnetInputStream is=ftpClient.list(); int c; while ((c=is.read())!=-1) { System.out.print((char) c);} is.close(); ftpClient.closeServer();//退出FTP服务器 } catch (IOException ex) {;} } (2)从FTP服务器上下传一个文件 void getButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClient ftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetInputStream is=ftpClient.get(filename); File file_out=new File(filename); FileOutputStream os=new FileOutputStream(file_out); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1) { os.write(bytes,0,c); } is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} } (3)向FTP服务器上上传一个文件 void putButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClient ftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetOutputStream os=ftpClient.put(filename); File file_in=new File(filename); FileInputStream is=new FileInputStream(file_in); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1){ os.write(bytes,0,c);} is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} } }

㈥ java实现ftp文件操作的方式有哪些

运用类的办法,编程人员能够长途登录到服务器,罗列该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵 盖了简直一切FTP的功用,FtpClient的实例变量保留了有关树立"署理"的各种信息。下面给出了这些实例变量:public static boolean useFtpProxy这个变量用于标明FTP传输过程中是不是运用了一个署理,因此,它实际上是一个符号,此符号若为TRUE,标明运用了一个署理主机。public static String ftpProxyHost此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机名。public static int ftpProxyPort此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机的端口地址。FtpClient有三种不同方式的结构函数,如下所示:1、public FtpClient(String hostname,int port)此结构函数运用给出的主机名和端口号树立一条FTP衔接。2、public FtpClient(String hostname)此结构函数运用给出的主机名树立一条FTP衔接,运用默许端口号。3、FtpClient()此结构函数将创立一FtpClient类,但不树立FTP衔接。这时,FTP衔接能够用openServer办法树立。一旦树立了类FtpClient,就能够用这个类的办法来翻开与FTP服务器的衔接。类ftpClient供给了如下两个可用于翻开与FTP服务器之间的衔接的办法。public void openServer(String hostname)这个办法用于树立一条与指定主机上的FTP服务器的衔接,运用默许端口号。

㈦ java FTP下载文件在代码中如何实现知道下载完成

(KmConfigkmConfig,StringfileName,StringclientFileName,OutputStreamoutputStream){try{StringftpHost=kmConfig.getFtpHost();intport=kmConfig.getFtpPort();StringuserName=kmConfig.getFtpUser();StringpassWord=kmConfig.getFtpPassword();Stringpath=kmConfig.getFtpPath();FtpClientftpClient=newFtpClient(ftpHost,port);//ftpHost为FTP服务器的IP地址,port为FTP服务器的登陆端口,ftpHost为String型,port为int型。ftpClient.login(userName,passWord);//userName、passWord分别为FTP服务器的登陆用户名和密码ftpClient.binary();ftpClient.cd(path);//path为FTP服务器上保存上传文件的路径。try{TelnetInputStreamin=ftpClient.get(fileName);byte[]bytes=newbyte[1024];intcnt=0;while((cnt=in.read(bytes,0,bytes.length))!=-1){outputStream.write(bytes,0,cnt);}//##############################################//这里文件就已经下载完了,自己理解一下//#############################################outputStream.close();in.close();}catch(Exceptione){ftpClient.closeServer();e.printStackTrace();}ftpClient.closeServer();}catch(Exceptione){System.out.println("下载文件失败!请检查系统FTP设置,并确认FTP服务启动");}}

㈧ java 下载异地FTP中的zip文件

好像需要一个支持jar包把,把ftp4j的下载地址贴出来

㈨ JAV中怎么实现FTP的下载功能

以下是这三部分的JAVA源程序:(1)显示FTP服务器上的文件 void ftpList_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); //输入的FTP服务器的IP地址 String user=userEdit.getText(); //登录FTP服务器的用户名 String password=passwordEdit.getText(); //登录FTP服务器的用户名的口令 String path=pathEdit.getText(); //FTP服务器上的路径 try { FtpClient ftpClient=new FtpClient(); //创建FtpClient对象 ftpClient.openServer(server); //连接FTP服务器 ftpClient.login(user, password); //登录FTP服务器 if (path.length()!=0) ftpClient.cd(path); TelnetInputStream is=ftpClient.list(); int c; while ((c=is.read())!=-1) { System.out.print((char) c);} is.close(); ftpClient.closeServer();//退出FTP服务器 } catch (IOException ex) {;} }(2)从FTP服务器上下传一个文件 void getButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClient ftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetInputStream is=ftpClient.get(filename); File file_out=new File(filename); FileOutputStream os=new FileOutputStream(file_out); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1) { os.write(bytes,0,c); } is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} }(3)向FTP服务器上上传一个文件 void putButton_actionPerformed(ActionEvent e) { String server=serverEdit.getText(); String user=userEdit.getText(); String password=passwordEdit.getText(); String path=pathEdit.getText(); String filename=filenameEdit.getText(); try { FtpClientftpClient=new FtpClient(); ftpClient.openServer(server); ftpClient.login(user, password); if (path.length()!=0) ftpClient.cd(path); ftpClient.binary(); TelnetOutputStream os=ftpClient.put(filename); File file_in=new File(filename); FileInputStream is=new FileInputStream(file_in); byte[] bytes=new byte[1024]; int c; while ((c=is.read(bytes))!=-1){ os.write(bytes,0,c);} is.close(); os.close(); ftpClient.closeServer(); } catch (IOException ex) {;} } }

㈩ linux下java实现ftp下载,ftpClient.listFiles();返回的数组长度一直是0

试过remote 被动模式吗。 因为环境的不同,别人难测试到同样的情形


赞 (0)