java ftpclient 池_FTPClient,连接池实现

直接贴代码:

import org.apache.commons.net.ftp.FTPClient;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import java.io.*;

/**

* FTP工具类

*/

@Component

public class FtpUtil {

/**

* 注入连接池对象

*/

@Autowired

private FTPClientPool ftpClientPool;

/**

* Description: 获取FTP文件流

* filePath格式 /xxx/xxx

*/

public byte[] getFileSteam(String filePath, String ftpName) throws Exception {

InputStream in = null;

byte[] bytes = null ;

FTPClient ftpClient = getFtpClient();

try {

// 使用相对路径

filePath = filePath.substring(1);

// 切换FTP目录

boolean change = ftpClient.changeWorkingDirectory(new String((filePath).getBytes("utf-8"), "iso-8859-1"));

if (change) {

in = ftpClient.retrieveFileStream(new String(ftpName.getBytes("utf-8"), "iso-8859-1"));

bytes = readStream(in);

} else {

throw new RuntimeException("获取文件输入流失败----原因----切换工作目录失败");

}

} catch (Exception e) {

throw new RuntimeException("获取文件输入流失败");

} finally {

ftpClientPool.returnObject(ftpClient);

in.close();

}

return bytes;

}

/**

* 输入流转输出流

*/

public static byte[] readStream(InputStream inStream) throws Exception {

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = -1;

while ((len = inStream.read(buffer)) != -1) {

outStream.write(buffer, 0, len);

}

outStream.close();

inStream.close();

你可能感兴趣的:(java,ftpclient,池)