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

 

你可能感兴趣的:(ftp 方式复制文件到本地)