`
yangyangmyself
  • 浏览: 232414 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Apache ftp tools 图片下载支持中文

    博客分类:
  • Java
阅读更多
写道
Apache Commom net:
1) 递归path,调用changeWorkingDirectory改变工作目录并验证是否存在
 然后直接调用retrieveFileStream(filename),filename不用带路径,path经过编码后,filename带全路径存在问题;
2)编码方式统一用new String(filename.getBytes("UTF-8"),"iso-8859-1")
3)ftpClient.getSystemType()获取FTP服务器操作系统,动态设置编码

 

写道
问题:1)原下载图片时直接返回InputStream,然后在业务代码位置获取数据时阻塞无响应,错误信息:toString() unavailable - no suspended threads

对于网络流InputStream available经常返回0,即网络存在延时,方法执行完后立刻关闭连接,数据还未接收完或正在接收中时被关闭,倒致InputStream read方法阻塞。

 

public static InputStream getBytes(URL url){
		FTPClient ftpClient = null;
		InputStream inputStream = null;
		String filename = null;
		String pathname = null;
		String fullpath = null;
		String host = url.getHost();
		String user = "anonymous";
		String pass ="";
		int port = url.getPort();
		String path = url.getPath();
		String userInfo = url.getUserInfo();
		try {
			if (userInfo != null) { // get the user and password
				int delimiter = userInfo.indexOf(':');
				if (delimiter != -1) {
					user = userInfo.substring(0, delimiter++);
					pass = userInfo.substring(delimiter);
				}
			}
			ftpClient = getClient(host, user, pass, port);
			if(!path.endsWith("/")){
				int i = path.lastIndexOf('/');
				if(i>0){
					filename=path.substring(i+1,path.length());
					pathname=path.substring(0,i);
				}else{
					filename=path;
					pathname=null;
				}
			} else {
				pathname=path.substring(0,path.length()-1);
				filename=null;
			}
			if(pathname!=null){
				fullpath=pathname+"/"+(filename!=null?filename:"");
			}else{
				fullpath = filename;
			}
			// 编码后的pathname
			StringBuffer sb = new StringBuffer();			
			ftpClient.setControlEncoding("UTF-8");
			String encodeFileName = new String(filename.getBytes("UTF-8"),FTP_ENCODE);
			StringTokenizer token = new StringTokenizer(path,"/");
			long a = System.currentTimeMillis();
			while (token.hasMoreTokens()){
				String fold = token.nextToken();
				// 中文编码
				String encodeFold = new String(fold.getBytes("UTF-8"),FTP_ENCODE);
				boolean flag = ftpClient.changeWorkingDirectory(encodeFold);
				if(!flag){
					System.out.println("目录不存在:"+fold);
					System.out.println("指定的目录不存在或ftp无法打开,路径为:"+pathname);
					break;
				}
				sb.append(encodeFold);
				if(token.hasMoreTokens()){
					sb.append("/");
				} else {
					sb.append("/");
					sb.append(encodeFileName);
				}
			}
			long b = System.currentTimeMillis();
			inputStream=ftpClient.retrieveFileStream(encodeFileName);
		} catch (FTPConnectionClosedException e) {
			System.err.println("Server closed connection.");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					// do nothing
				}
			}
		}
		return inputStream;
	}

 

写道
数据获取完后,再关闭连接。升级后正常

 

package com.sunshine.app.util.ftp;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.StringTokenizer;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPConnectionClosedException;
import org.apache.commons.net.ftp.FTPReply;

public abstract class FtpTools {

	private static String FTP_ENCODE = "iso-8859-1";
	
	private static byte[] EMPTY_BYTE = new byte[0];
	
	public static FTPClient getClient(String host, String user, String pass, int port){
		FTPClient ftpClient = null;
		ftpClient = new FTPClient();
		try {
			ftpClient.connect(host, port);
			int defaultTimeout = 30 * 60 * 1000;
			ftpClient.setConnectTimeout(3 * 1000);
			ftpClient.setControlKeepAliveTimeout(defaultTimeout);
			ftpClient.setControlKeepAliveReplyTimeout(defaultTimeout);			
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.err.println("FTP server refused connection.");
			}
		} catch (IOException e) {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					// do nothing
				}
			}
			System.err.println("Could not connect to server.");
			e.printStackTrace();
		}
		try
        {
            if (!ftpClient.login(user, pass)){
                ftpClient.logout();
            }
            System.out.println("Remote system is " + ftpClient.getSystemType());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);        
            // Use passive mode as default because most of us are
            // behind firewalls these days.
            //ftpClient.enterLocalActiveMode();
            ftpClient.enterLocalPassiveMode();
            ftpClient.setUseEPSVwithIPv4(false);
        }catch(FTPConnectionClosedException e){
            System.err.println("Server closed connection.");
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
		} finally {
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					// do nothing
				}
			}
		}
		return ftpClient;
	}
	
	public static byte[] getBytes(URL url){
		FTPClient ftpClient = null;
		InputStream inputStream = null;
		String filename = null;
		String pathname = null;
		String fullpath = null;
		String host = url.getHost();
		String user = "anonymous";
		String pass ="";
		int port = url.getPort();
		String path = url.getPath();
		String userInfo = url.getUserInfo();
		try {
			if (userInfo != null) { // get the user and password
				int delimiter = userInfo.indexOf(':');
				if (delimiter != -1) {
					user = userInfo.substring(0, delimiter++);
					pass = userInfo.substring(delimiter);
				}
			}
			ftpClient = getClient(host, user, pass, port);
			if(!path.endsWith("/")){
				int i = path.lastIndexOf('/');
				if(i>0){
					filename=path.substring(i+1,path.length());
					pathname=path.substring(0,i);
				}else{
					filename=path;
					pathname=null;
				}
			} else {
				pathname=path.substring(0,path.length()-1);
				filename=null;
			}
			if(pathname!=null){
				fullpath=pathname+"/"+(filename!=null?filename:"");
			}else{
				fullpath = filename;
			}
			// 编码后的pathname
			StringBuffer sb = new StringBuffer();			
			ftpClient.setControlEncoding("UTF-8");
			String encodeFileName = new String(filename.getBytes("UTF-8"),FTP_ENCODE);
			StringTokenizer token = new StringTokenizer(path,"/");
			long a = System.currentTimeMillis();
			while (token.hasMoreTokens()){
				String fold = token.nextToken();
				// 中文编码
				String encodeFold = new String(fold.getBytes("UTF-8"),FTP_ENCODE);
				boolean flag = ftpClient.changeWorkingDirectory(encodeFold);
				if(!flag){
					System.out.println("目录不存在:"+fold);
					System.out.println("指定的目录不存在或ftp无法打开,路径为:"+pathname);
					break;
				}
				sb.append(encodeFold);
				if(token.hasMoreTokens()){
					sb.append("/");
				} else {
					sb.append("/");
					sb.append(encodeFileName);
				}
			}
			long b = System.currentTimeMillis();
			inputStream=ftpClient.retrieveFileStream(encodeFileName);
			long c = System.currentTimeMillis();
			System.out.println("CD--"+(b-a) + " RF--" + (c-b));
			if(inputStream == null)
				return EMPTY_BYTE;
			return transferToByteArray(inputStream);
		} catch (FTPConnectionClosedException e) {
			System.err.println("Server closed connection.");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			
			if (ftpClient.isConnected()) {
				try {
					ftpClient.disconnect();
				} catch (IOException f) {
					// do nothing
				}
			}
		}
		return EMPTY_BYTE;
	}
	
	public static byte[] transferToByteArray(InputStream input){
		BufferedInputStream bi = null;
		ByteArrayOutputStream barray = null;
		try {
			byte[] buffer = new byte[1024];
			bi = new BufferedInputStream(input); 
			barray = new ByteArrayOutputStream();
			int len = 0;
			while((len=bi.read(buffer))!=-1){
				barray.write(buffer, 0, len);
			}
			barray.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(barray != null)
					barray.close();
				if(bi != null)
					bi.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return barray.toByteArray();
	}
}

 

 

0
0
分享到:
评论

相关推荐

    apache-cxf-3.2.1-src.tar.gz

    总的来说,Apache CXF是一个强大的工具,不仅提供了全面的Web服务支持,还具有高度可扩展性和灵活性,使得开发者在构建和维护Web服务时能够拥有更多的选择和控制。对于希望深入理解Web服务技术或想要定制化开发的...

    centos安装apache

    在IT行业中,CentOS是一个广泛使用的Linux发行版,它以其稳定性、安全性以及对服务器环境的良好支持而备受青睐。Apache HTTP Server则是全球最流行的Web服务器软件,它免费且开源,能够处理各种HTTP请求,为用户提供...

    Apache和Tomcat集群配置步骤(Apache2.2,Tomcat6.0).

    - Linux平台: 下载 `apache-tomcat-6.0.32.tar.gz` 并将其保存在 `/usr/local` 目录下。 #### 二、软件安装 **1. 安装Apache** - **Windows下安装**: - 使用MSI安装程序安装Apache,并设置其运行在80端口作为...

    D:\tools\apache-jmeter-5.5\bin\jmeter.bat

    标题中的"D:\tools\apache-jmeter-5.5\bin\jmeter.bat"是指Apache JMeter工具的启动脚本,通常用于在Windows环境下运行JMeter。这个文件是JMeter的命令行版本,允许用户通过命令行界面执行性能测试。Apache JMeter是...

    hadoop0.23.9离线api

    org.apache.hadoop.fs.ftp org.apache.hadoop.fs.http.client org.apache.hadoop.fs.http.server org.apache.hadoop.fs.kfs org.apache.hadoop.fs.permission org.apache.hadoop.fs.s3 org.apache.hadoop.fs....

    apache-cxf-2.7.18-src.zip 源码

    Apache CXF 是一个开源的Java框架,用于构建和开发服务导向架构(Service-Oriented Architecture, SOA)和Web服务。源码包"apache-cxf-2.7.18-src.zip"包含了CXF框架的核心组件和相关模块,是深入理解CXF工作原理和...

    apache-cxf-2.2.6.zip webservice cxf开发利器完整开发包

    9. **API文档和社区支持**:Apache CXF拥有详尽的API文档和活跃的社区,为开发者提供了丰富的学习资源和问题解答支持。 总的来说,"apache-cxf-2.2.6.zip"这个压缩包包含了所有必要的库和配置文件,让开发者能够...

    Apache Jmeter使用指南.pdf

    Apache JMeter是一款开源的性能测试工具,它主要用于测试静态和动态资源的性能,比如静态文件、Java小服务程序、CGI脚本、Java对象、数据库、FTP服务器等。JMeter用于模拟高负载下的各种行为,并测量其性能,可以...

    test tools.zip

    "test tools.zip"这个压缩包可能包含了多种用于Linux环境的测试工具,主要用于压力测试。压力测试是一种评估系统在高负载或大量并发请求下的性能和稳定性的测试方法。 一、压力测试工具 1. **Apache JMeter**:这...

    linux下安装jdk及配置环境变量及apache-tomact的安装

    在Linux环境下,安装Java Development Kit (JDK) 和Apache Tomcat是进行Web应用程序开发和部署的基础。下面将详细讲解这两个组件的安装过程。 首先,我们来看JDK的安装步骤: 1. **下载JDK**: 从SUN的官方网站...

    用Apache AXIS 开发 Web Services Step By Step

    ### 使用Apache Axis开发Web Services 步骤详解 #### 一、环境准备 在开始使用Apache Axis开发Web Services之前,需要确保开发环境已经搭建好。本文档将详细介绍如何配置必要的环境。 **1.1 软件下载准备** - **...

    apache-cxf-2.2.10.zip

    Apache CXF 是一个开源的Java框架,用于构建和开发服务导向架构(Service-Oriented Architecture, SOA)和Web服务。这个"apache-cxf-2.2.10.zip"压缩包包含了Apache CXF 2.2.10版本的所有组件和资源。CXF允许开发者...

    apache-jmeter-5.4.zip

    Apache JMeter支持多种协议和应用类型,包括HTTP、HTTPS、FTP、JDBC、SMTP等,因此可以对Web服务器、数据库、网络设备等多种服务进行测试。 JMeter的工作原理是模拟多个并发用户对目标系统发起请求,通过收集和分析...

    apache-jmeter-3.1.7z

    - `apache-jmeter-3.1.tgz.asc`:这是GPG签名文件,用于验证下载的文件是否完整且未被篡改。通过与发布者的公钥对比,可以确认文件的真实性。 - `apache-jmeter-3.1.tgz.md5`:MD5校验和文件,提供每个文件的MD5...

    apache-jmeter-2.12.tgz

    Apache JMeter是一款强大的开源性能测试工具,主要用于模拟大量并发用户对Web应用进行负载和压力测试。这个"apache-jmeter-2.12.tgz"压缩包包含的是JMeter的2.12版本,该版本发布于2014年,是JMeter历史上的一个重要...

    Apache2.4.10+PHP5.4.23+mysql-5.6.10+Zend Guard Loader6)_20141027.docx

    - 下载Apache源代码: ``` wget http://apache.mirrors.hoobly.com/httpd/httpd-2.4.10.tar.gz ``` - 解压并进入目录: ``` tar zxf httpd-2.4.10.tar.gz cd httpd-2.4.10 ``` - 配置、编译和安装: ``` ./configure...

    linux_asp.net_Tools_linux.rar_linux asp

    本压缩包"linux_asp.net_Tools_linux.rar_linux asp"提供了一些工具和资源,帮助开发者在Linux系统上配置和运行ASP.NET应用。 1. **ASP.NET on Linux**: ASP.NET是Microsoft开发的一种用于构建Web应用程序的框架,...

    MxSrvs For Mac_v1.1.0

    开发者可以通过FTP协议上传和下载项目文件,实现与远程服务器的同步,这对于协作开发和部署项目尤其有用。 MxSrvs For Mac_v1.1.0的压缩包文件名为"MxSrvs For Mac_v1.1.0.dmg",这是一个标准的Mac OS Disk Image...

Global site tag (gtag.js) - Google Analytics