ftp工具类

       文章主要介绍ftp工具类,主要包括FTPUtil工具类使用实例、FTP连接、FTP上传文件、下载文件等,具有一定的参考价值,需要的朋友可以参考一下。

public class FTPUtil {

private final Logger logger = LoggerFactory.getLogger(FTPUtil.class); 

private static String encoding = "UTF-8";

/**

* ftp客户端

*/

FTPClient ftpClient;

/**

* ftp服务器地址

*/

private String host;

/**

* ftp 端口号 默认21

*/

private int port = 21;

/**

* ftp服务器用户名

*/

private String username;

/**

* ftp服务器密码

*/

private String password;

/**

* ftp远程目录

*/

private String remoteDir;

/**

* 本地存储目录

*/

private String localDir;

/**

* 文件路径通配符 默认列出所有

*/

private String regEx = "*";

/**

* 指定要下载的文件名

*/

private String downloadFileName;

public FTPUtil setConfig(String host, String username, String password) {

this.host = host;

this.username = username;

this.password = password;

return this;

}

public FTPUtil setConfig(String host, int port, String username,String password) {

this.host = host;

this.port = port;

this.username = username;

this.password = password;

return this;

}

private void connectServer() throws Exception{

if(this.ftpClient == null) {

this.ftpClient = new FTPClient();

}

//设置超时时间

this.ftpClient.setConnectTimeout(30000);

try {

// 1、连接服务器

if(!this.ftpClient.isConnected()){

// 如果采用默认端口,可以使用client.connect(host)的方式直接连接FTP服务器

this.ftpClient.connect(this.host, this.port);

// 登录

this.ftpClient.login(this.username, this.password);

// 获取ftp登录应答码

int reply = this.ftpClient.getReplyCode();

// 验证是否登陆成功

if (!FTPReply.isPositiveCompletion(reply)) {

logger.info("未连接到FTP,用户名或密码错误。");

this.ftpClient.disconnect();

throw new RuntimeException("未连接到FTP,用户名或密码错误。");

} else {

logger.info("FTP连接成功。IP:"+host +"PORT:" +port);

}

// 2、设置连接属性

this.ftpClient.setControlEncoding(FTPUtil.encoding);

// 设置以二进制方式传输

this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 

this.ftpClient.enterLocalPassiveMode();

}

} catch (Exception e) {

try {

this.ftpClient.disconnect();

} catch (IOException e1) {

}

logger.error("连接FTP服务器出现异常,参数:ip="+this.host+",port="+this.port+",user="+this.username+",password="+this.password);

}

}

public List<String> fileReaderByRow(String remoteFileName)throws Exception{

if(remoteFileName == null || "".equals(remoteFileName.trim())) {

}else {

List<String> rowList = new ArrayList<String>();

InputStream input = null;

BufferedReader reader = null;

this.connectServer();

InputStream is = null;

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、设置文件名通配符

this.regEx = remoteFileName+"*";

// 3、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length == 0) {

logger.warn("文件数为0,没有可下载的文件!");

return null;

}else if(ftpFiles.length > 1) {

logger.warn("文件数为"+ftpFiles.length+"个,并不是唯一文件!");

return null;

}else {

logger.info("准备下载" + ftpFiles.length + "个文件");

// 4、获得文件流读取文件内容

FTPFile file = ftpFiles[0];

is = this.ftpClient.retrieveFileStream(file.getName());

if(is==null){

throw new RuntimeException("下载失败,检查文件是否存在");

}

//将流整体读取。

reader = new BufferedReader(new InputStreamReader(is,"utf-8"));

String str;

//判断是否是最后一行

while((str=reader.readLine())!=null){

// logger.debug("输出每一行内容:"+str);//输出每一行内容。

rowList.add(str);

}

}

} catch (IOException ex) {

logger.error("ftp文件行集记录读取出现异常,参数remoteFileName="+remoteFileName);

} finally {

try {

if (input != null) {

input.close();

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if(reader != null) {

reader.close();

}

}catch (Exception e) {

e.printStackTrace();

}

}

}

return rowList;

}

}

public void uploadRowValueList(String remoteFileName, List<String> rowValueList)throws Exception{

if(remoteFileName == null || "".equals(remoteFileName.trim())) {

}else if(rowValueList == null || rowValueList.size() == 0){

}else {

OutputStream os = null;

BufferedWriter bw = null;

try {

this.connectServer();

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 将远程文件加入输出流中

os = this.ftpClient.storeFileStream(remoteFileName);

if(os == null) {

throw new RuntimeException("上传失败,请检查是否有上传权限");

}

// 创建一个缓冲区

bw = new BufferedWriter(new OutputStreamWriter(os));

for (String rowValue : rowValueList) {

bw.write(rowValue+"\r\n");

}

bw.flush();

} catch (Exception ex) {

logger.error("ftp上传行值记录集出现异常,参数remoteFile="+remoteFileName+",rowValueList="+rowValueList);

} finally {

try {

if (os != null) {

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}finally {

try {

if (bw != null) {

bw.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

}

public List<File> download()throws Exception{

List<File> files = null;

this.connectServer();

InputStream is = null;

File downloadFile = null;

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return null;

}

logger.info("准备下载" + ftpFiles.length + "个文件");

// 3、保存文件到本地

for (FTPFile file : ftpFiles) {

//如果有指定下载的文件

if(!StrUtil.isNullOrEmpty(this.downloadFileName) && !file.getName().equals(this.downloadFileName)){

continue;

}

if(files == null) files = new ArrayList<File>();

is = this.ftpClient.retrieveFileStream(file.getName());

if(is==null) {

throw new RuntimeException("下载失败,检查文件是否存在");

}

downloadFile = new File(this.localDir + file.getName());

FileOutputStream fos = FileUtils.openOutputStream(downloadFile);

IOUtils.copy(is, fos);

this.ftpClient.completePendingCommand();

IOUtils.closeQuietly(is);

IOUtils.closeQuietly(fos);

files.add(downloadFile);

}

logger.info("文件下载成功,下载文件路径:" + this.localDir);

} catch (IOException e) {

logger.error("ftp下载文件出现异常,参数remoteDir="+this.remoteDir+",localDir="+this.localDir+",regEx="+this.regEx+",downloadFileName="+this.downloadFileName);

}

return files;

}

public List<File> download(String remoteDir,String localDir)throws Exception{

this.remoteDir = remoteDir;

this.localDir = localDir;

return this.download();

}

public List<File> download(String remoteDir,String regEx,String localDir)throws Exception{

this.remoteDir = remoteDir;

this.localDir = localDir;

this.regEx = regEx;

return this.download();

}

public List<File> download(String downloadFileName)throws Exception{

this.downloadFileName = downloadFileName;

return this.download();

}

public void upload(List<File> files)throws Exception{

OutputStream os = null;

try {

// 2、取本地文件

if(files == null || files.size()==0) {

logger.warn("文件数为0,没有找到可上传的文件");

return;

}

logger.info("准备上传" + files.size() + "个文件");

// 3、上传到FTP服务器

for(File file : files){

this.connectServer();

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

os = this.ftpClient.storeFileStream(file.getName());

if(os== null) {

throw new RuntimeException("上传失败,请检查是否有上传权限");

}

IOUtils.copy(new FileInputStream(file), os);

IOUtils.closeQuietly(os);

}

logger.info("文件上传成功,上传文件路径:" + this.remoteDir);

} catch (IOException e) {

logger.error("ftp上传文件出现异常,参数remoteDir="+this.remoteDir+",files="+files);

}

}

public void upload(List<File> files,String remoteDir)throws Exception{

this.remoteDir = remoteDir;

this.upload(files);

}

public void upload(File file)throws Exception{

List<File> files = new ArrayList<File>();

files.add(file);

this.upload(files);

}

public OutputStream getOutputStream(String fileName)throws Exception{

OutputStream os = null;

this.connectServer();

// 1、设置远程FTP目录

try {

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

os = this.ftpClient.storeFileStream(fileName);

if(os== null) {

throw new RuntimeException("服务器上创建文件对象失败");

}

return os;

} catch (IOException e) {

logger.error("服务器上创建文件对象失败" + e.getMessage());

}

}

    public boolean isFileExist(String fileName)throws Exception{


    boolean result = false;

this.connectServer();

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return result;

}

// 3、检查文件是否存在

for (FTPFile file : ftpFiles) {

if(file.getName().equals(fileName)){

result = true;

break;

}

}

} catch (Exception e) {

logger.error("检查文件是否存在失败" + e.getMessage());

}


    return result;

    }


    public boolean isFileExistByRegExName(String fileName)throws Exception{


    boolean result = false;

this.connectServer();

try {

// 1、设置远程FTP目录

this.ftpClient.changeWorkingDirectory(this.remoteDir);

logger.info("切换至工作目录【" + this.remoteDir + "】");

// 2、读取远程文件

FTPFile[] ftpFiles = this.ftpClient.listFiles(this.regEx);

if(ftpFiles.length==0) {

logger.warn("文件数为0,没有可下载的文件!");

return result;

}

// 3、检查文件是否存在

for (FTPFile file : ftpFiles) {

if(file.getName().indexOf(fileName) != -1){

result = true;

break;

}

}

} catch (Exception e) {

logger.error("检查文件是否存在失败" + e.getMessage());

}


    return result;

    }

    public void closeConnect() {

        try {

        this.ftpClient.disconnect();

logger.info(" 关闭FTP连接!!! ");

} catch (IOException e) {

logger.warn(" 关闭FTP连接失败!!! ",e);

}

    }


public String getRemoteDir() {

return remoteDir;

}

public void setRemoteDir(String remoteDir) {

this.remoteDir = remoteDir;

}

public String getLocalPath() {

return localDir;

}

public void setLocalPath(String localPath) {

this.localDir = localPath;

}

public String getDownloadFileName() {

return downloadFileName;

}

public void setDownloadFileName(String downloadFileName) {

this.downloadFileName = downloadFileName;

}

public String getRegEx() {

return regEx;

}

public void setRegEx(String regEx) {

this.regEx = regEx;

}

@Override

public String toString() {

return "FTPUtil [host=" + this.host + ", port=" + this.port + ", username="

+ this.username + ", password=" + this.password + "]";

}

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容