这里有新鲜出炉的Java并发编程示例,程序狗速度看过来!
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
这篇文章主要介绍了Java实现ftp文件上传下载解决慢中文乱码多个文件下载等问题的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下
废话不多说了,直接给大家贴代码了,具体代码如下所示:
- //文件上传
- public static boolean uploadToFTP(String url,int port,String username,String password,String path,String filename,InputStream input)
- {
- boolean success=false;
- FTPClient ftp=new FTPClient();//org.apache.commons.net.ftp
- try{
- if(port>-1)
- {
- ftp.connect(url,port);
- }else{
- ftp.connect(url);//ftp默认的端口是21
- }
- //很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
- if(ftp.login(username,password))
- {
- ftp.enterLocalActiveMode();
- ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
- //创建目录,如果存在会返回失败
- ftp.makeDirectory(path);
- //切换目录
- ftp.changeWorkingDirectory(path);
- //上传文件
- //FTP协议规定文件编码格式为ISO-8859-1
- filename=new String(filename.getBytes("GBK"),"ISO-8859-1");
- OutputStream out=ftp.storeFileStream(filename);
- byte[]byteArray=new byte[4096];
- int read=0;
- while((read=input.read(byteArray))!=-1)
- {
- out.write(byteArray,0,read);
- }
- out.close();
- ftp.logout();
- sucess=true;
- }
- }
- catch(Exception e)
- {
- }
- finally{
- if(ftp.isConnected())
- {
- ftp.disConnecct();
- }
- }
- }
- //文件下载
- public static boolean downloadFromFTP(String url,int port,String username,String password,String path,String localpath)
- {
- boolean success=false;
- FTPClient ftp=new FTPClient();//org.apache.commons.net.ftp
- try{
- int reply;
- if(port>-1)
- {
- ftp.connect(url,port);
- }else{
- ftp.connect(url);//ftp默认的端口是21
- }
- //很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
- ftp.login(username,password)
- ftp.enterLocalActiveMode();
- ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
- reply=ftp.getReplyCode();
- if(!FTPReply.isPositionCompletion(reply))
- {
- ftp.disconnect();
- return success;s
- }
- //切换目录 此处可以判断,切换失败就说明ftp上面没有这个路径
- ftp.changeWorkingDirectory(path);
- //上传文件
- FTPFile[]fs=ftp.listFiles();
- OutputStream out=null;
- InputStream in=null;
- for(int i=0;i<fs.length;i++)
- {
- FTPFile ff=fs[i];
- String outFileName=ff.getName();
- //创建本地的文件时候要把编码格式转回来
- String localFileName=new String(ff.getName().getBytes("ISO-8859-"),"GBK");
- File localFile=new File(localpath+lcoalFileName);
- out=new FileOutputStream(localFile);
- in=ftp.retrieveFileStream(outFileName);
- byte[]byteArray=new byte[4096];
- int read=0;
- while((read=in.read(byteArray))!=-1)
- {
- out.write(byteArray,0,read);
- }
- //这句很重要 要多次操作这个ftp的流的通道,要等他的每次命令完成
- ftp.completePendingCommand();
- out.flush();
- out.close();
- ftp.logout();
- sucess=true;
- }
- catch(Exception e)
- {
- }
- finally{
- if(ftp.isConnected())
- {
- ftp.disConnecct();
- }
- }
- }
以上所述是小编给大家介绍的Java实现ftp文件上传下载解决慢中文乱码多个文件下载等问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHPERZ网站的支持!
来源: http://www.phperz.com/article/17/1111/359690.html