解决FTP服务器上中文名文件下载后为空的问题

有台服务器,编码为GBK,发现服务器上的中文文件下载后文件大小为0,打开为空白。

经调查,是文件名编码格式不对导致,对于中文情况,使用FTPClient时编码格式需使用ISO-8859-1

具体代码:

package com.neusoft.ftptest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpMain {

	public static void main(String[] args) {
		FTPClient client = new FTPClient();
		try {
			client.connect("10.10.xxx.xxx", 21);
			client.login("administrator", "xxx");
			System.out.println(client.getControlEncoding());
			int reply = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				client.disconnect();
				System.out.println("Login error");
				return;
			}
			client.setControlEncoding("GBK");
			// client.segt

			System.out.println(client.getCharsetName());
			// client.enterRemotePassiveMode();
			client.enterLocalPassiveMode();
			client.changeWorkingDirectory("11_COMMUNICATION/201204");

			System.out.println("---------------------------------------");

			String[] names;

			names = client.listNames();
			for (int i = 0; i < names.length; i++) {
				System.out.println(names[i]);
			}
			System.out.println(names.toString());

			System.out.println("---------------------------------------");

			FTPFile f = client.listFiles()[0];
			System.out.println(f.getLink());
			client.changeWorkingDirectory("/");
			String path = "/10_NOTICE_FILE/201706";
			// String path = "/10_NOTICE_FILE/201203/";

			client.setBufferSize(1024);
			client.setFileType(FTP.BINARY_FILE_TYPE);
			client.enterLocalPassiveMode();
			client.changeWorkingDirectory(path);

			FTPFile[] fs = client.listFiles();
			FileOutputStream out = null;
			InputStream in = null;
			for (int i = 0; i < fs.length; i++) {
				FTPFile ff = fs[i];
				String outFileName = ff.getName();
				System.out.println(outFileName);

				//本地目录文件不需要编码
				File localFile = new File("D:\\ftp\\" + ff.getName());
				OutputStream fos = new FileOutputStream(localFile);
				// ftp需使用ISO-8859-1编码格式
				String localFileName = new String(ff.getName().getBytes("GBK"), "ISO-8859-1");
				client.retrieveFile(localFileName, fos);
				fos.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				client.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值