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

	}

}

你可能感兴趣的:(Java)