ftp 方式复制文件到本地

public static byte[] copyFile(String fileName) throws Exception {
		 // 建立连接
        connectToServer();
		ftpClient.enterLocalPassiveMode();
		//ftpClient.setControlEncoding("UTF-8");
		
		ftpClient.changeWorkingDirectory(CURRENT_DIR);
		byte[] return_arraybyte = null;
		if (ftpClient != null) {
			try {
				FTPFile[] files = ftpClient.listFiles();
				for (FTPFile file : files) {
					String f=new String(file.getName().getBytes("iso-8859-1"),"utf-8");//防止乱码
					System.out.println(f);
					System.out.println(f.equals(fileName));
					if (f.equals(fileName)) {
						InputStream ins = ftpClient.retrieveFileStream(file.getName());//需使用file.getName获值,若用f会乱码
						ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
						byte[] buf = new byte[204800];
						int bufsize = 0;
						while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {
							byteOut.write(buf, 0, bufsize);
						}
						return_arraybyte = byteOut.toByteArray();

						//File localFile = new File(LOCAL_PATH +File.separator+ f);
						//OutputStream is = new FileOutputStream(localFile);
						
						//ftpClient.retrieveFile(f, is);
						
						//FileUtils.copyInputStreamToFile(ins, localFile);
						
						//is.flush();
						//is.close();
						
						byteOut.close();
						ins.close();
					    ftpClient.completePendingCommand();
						break;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				closeConnect();
			}
		}
		
		ByteArrayInputStream bts = new ByteArrayInputStream(return_arraybyte);	
		
		File localFile = new File(LOCAL_PATH +File.separator+ fileName);
		
		FileUtils.copyInputStreamToFile(bts, localFile);
		
		
		return return_arraybyte;
	}

关闭输入流之后返回的inputStream对象为空,用bytes保存后返回出去再new ByteArrayInputStream(bytes); 方法可以获得输入流

 

为什么要执行inputStream.close();再执行ftp.completePendingCommand()

commons-net的FTPClient,在使用public InputStream retrieveFileStream(String remote)
方法时需要特别注意,在调用这个接口后,一定要手动close掉返回的InputStream,然后再调用completePendingCommand方法

 

https://blog.csdn.net/wangjian5748/article/details/3404619

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值