FTP的多线程下载,之前一直使用的是FTP4j觉得蛮好用的,但是在处理多线程问题时,FTP4j就显得很弱了,因此改用Apache 的commons.Net 2.2来实现。
后来发现commons.net2.2在多线程方面实现起来的确比ftp4j简单。
public static void main(String[] args) {
try {
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("gbk");
ftpClient.connect("192.168.1.3");
ftpClient.login("h3c", "human520");
//获得文件大小
FTPFile[] ftpFile = ftpClient.listFiles("ftp4j-中文测试.zip");
System.out.println(ftpFile[0].getSize());
File outfile = new File("C:/Users/Administrator/Desktop/test.zip");
FileOutputStream out = new FileOutputStream(outfile);
ftpClient.setRestartOffset(10240); //从这里开始
InputStream in = ftpClient.retrieveFileStream("ftp4j-中文测试.zip");
byte[] bytes = new byte[1024];
int c;
int s = 0;
while((c = in.read(bytes))!= -1){
out.write(bytes,0,c);
s+=c;
if(s==10240){
break; //到这里结束
}
}
System.out.println(s);
// ftpClient.retrieveFile("ftp4j-中文测试.zip", oStream); //一次性下载完
out.close();
in.close();
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (SocketException e) {
// TODO Auto-generated catch block
System.out.println("SocketException");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException");
e.printStackTrace();
}
} |
|