linux wget命令下发FTP时,包含中文路径提示文件不存在,无法下载文件解决方法

文件不存在的原因是因为编码不同,服务器认为请求地址的文件不存在。

解决方法是使用服务可以理解的方式对路径进行编码(我的ftp服务器使用的是gb2312),例如使用java先把中文路径转换为英文再调用wget进行下载:

package c;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class FTPGb2312 {

	public static void main(String[] args) {
		BufferedReader read2=null;
		BufferedReader read1=null;
		try {
			System.out.println("[info]:args[0]"+args[0]);
			args[0]=getPath(args[0]);
			System.out.println("[info]:args[0]"+args[0]);
			System.out.println("[info]:args[1]"+args[1]);
			Runtime r = Runtime.getRuntime();
			Process p=r.exec("wget --restrict-file-names=nocontrol ftp://10.231.155.209"+args[0]+" -O "+args[1]);
			read1 = new BufferedReader(new InputStreamReader(p.getInputStream(),"UTF-8"));
			String s=null;
			while((s=read1.readLine())!=null){
				System.out.println("[info]:"+s);
			}
			
			read2 = new BufferedReader(new InputStreamReader(p.getErrorStream(),"UTF-8"));
			
			while((s=read2.readLine())!=null){
				System.out.println("[info]:"+s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
			if(read1!=null){
				read1.close();
			}
			}catch(Exception e){}
			try{
			if(read2!=null){
				read2.close();
			}
			}catch(Exception e){}
		}
		
	}

	private static String getPath(String str) throws UnsupportedEncodingException {
		String[] strs=str.split("/");
		List<String> l=new ArrayList<String>();
		StringBuffer sb=new StringBuffer();
		sb.append("/");
		for (int i = 0; i < strs.length; i++) {
			if(strs[i]!=null&&!strs[i].equals("")){
				l.add(URLEncoder.encode(strs[i], "gb2312"));
			}
		}
		for (String s:l){
			sb.append("/");
			sb.append(s);
		}
		return sb.toString();
	}
}

 使用

java  -jar c.FTPGb2312 ftp路径 目标文件路径

代替 wget  ftp路径 -O 目标文件路径

即可实现正常下载

猜你喜欢

转载自bnmnba.iteye.com/blog/2401589