初步解决common-net.jar开发ftp时上传文件损坏问题

刚开始接触用common-net.jar进行ftp开发,就遇到了上传下载文件损坏的问题,除了txt文件外,其他类型文件均损坏,且上传下载的文件比原始文件大。偶然间发现,如果调用了FTPClient.logout(),就解决了问题,但是在单一线程中下载多个文件却没有成功,还请高手指点迷津。代码如下:
package com.yct.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.Util;
import org.junit.Test;

public class FtpClientTry {

@Test
public void test() throws Exception{
FTPClient ftpClient = new FTPClient();

int len;
String filename;

InetAddress host = InetAddress.getByName("192.168.0.1");
       
ftpClient.connect(host, 2121);
ftpClient.login("admin", "admin");
//设置被动模式
ftpClient.enterLocalPassiveMode();

//设置以二进制方式传输  
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 

FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
System.out.println(ftpClient.getReplyCode());
if(file.getType() == FTPFile.FILE_TYPE){
String filename1 = file.getName();
filename = new String(filename1.getBytes("iso-8859-1"), "utf-8");
System.out.println(filename);

InputStream is = ftpClient.retrieveFileStream(filename1);

OutputStream local = new FileOutputStream("d:/"+filename);

Util.copyStream(is, local);

}
}
ftpClient.logout();//必须logout,否则文件损坏
ftpClient.disconnect();
}
}

                            

你可能感兴趣的:(java,common,FTPClient)