java ftp deletefile_java ftp实现文件上传和删除

package com.tw.ftp;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.apache.commons.io.IOUtils;

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

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

/**

*

ftp连接管理(使用apache commons-net-1.4.1 lib)

*@author tangw 2010-12-26

*

*/

public class FtpConManager {

private static FtpConManager instance;

private FTPClient ftpClient =null;

/**

* get FtpConManager

* @return FtpConManager

*/

public synchronized static FtpConManager getInstance(){

if( instance == null ){

instance = new FtpConManager();

}

return instance;

}

/**

*

ftp登录

* @param s_url ftp服务地址

* @param uname 用户名

* @param pass 密码

*/

public void login(String s_url,String uname,String pass){

ftpClient = new FTPClient();

try{

//连接

ftpClient.connect(s_url);

ftpClient.login(uname,pass);

//检测连接是否成功

int reply = ftpClient.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)) {

this.closeCon();

System.err.println("FTP server refused connection.");

System.exit(1);

}

}catch(Exception ex){

ex.printStackTrace();

//关闭

this.closeCon();

}

}//end method login

/**

*

ftp上传文件

* @author tangw 2010-12-26

* @param srcUrl 须上传文件

* @param targetFname 生成目标文件

* @return true||false

*/

public boolean uploadFile(String srcUrl,String targetFname){

boolean flag = false;

if( ftpClient!=null ){

File srcFile = new File(srcUrl);

FileInputStream fis = null;

try {

fis = new FileInputStream(srcFile);

//设置上传目录

ftpClient.changeWorkingDirectory("/ImData/");

ftpClient.setBufferSize(1024);

ftpClient.setControlEncoding("GBK");

//设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

//上传

flag = ftpClient.storeFile(targetFname, fis);

} catch (Exception e) {

e.printStackTrace();

this.closeCon();

}finally{

IOUtils.closeQuietly(fis);

}

}

return flag;

}//end method uploadFile

/**

*

*

删除ftp上的文件

* @author tangw 2010-12-26

* @param srcFname

* @return true || false

*/

public boolean removeFile(String srcFname){

boolean flag = false;

if( ftpClient!=null ){

try {

flag = ftpClient.deleteFile(srcFname);

} catch (IOException e) {

e.printStackTrace();

this.closeCon();

}

}

return flag;

}//end method removeFile

/**

*

销毁ftp连接

*@author tangw 2010-12-26

*/

public void closeCon(){

if(ftpClient !=null){

if(ftpClient.isConnected()){

try {

ftpClient.logout();

ftpClient.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}//end method closeCon

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值