用FTPClient的来上传下载文件

ftp上传与下载,这里用到的是org.apache.commons.net.ftp.FTPClient工具类,.

上传的思路:1.创建FTPClient对象,2.建立连接(对应的ipport)3.登陆(usernamepassword)4.得到返回值(ftp.getReplyCode())5.判断这个返回值是不是有意义的(FTPReply.isPositiveCompletion(reply))如果没有意义就是没有完成的话,断开ftp连接,返回false 6.如果应答码有意义则更改路径(ftp服务器的路径),保存文件7.关闭输入流,退出登录,更改返回状态为true 8.断开ftp连接

public static boolean uploadFile(String url,int port,String username,String password,String path,String fileName,InputStream in){

boolean success = false;

FTPClient ftp = new FTPClient();

try{

int reply;

ftp.connect(url,port);

ftp.login(username,password);

reply = ftp.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)){

ftp.disconnect();

return success;

}

ftp.changeWorkingDirectory(path);

ftp.storeFile(fileName,in);

 

in.close();

ftp.logout();

success=true;

 

}catch(IOException e){

e.printStackTrace();

}finally{

if(ftp.isConnected()){

ftp.disconnect();

}catch(IOException e){}

}

return success;

}

 

ftp下载1.创建FTPClient对象2.连接(url,port)3.登陆(username,password)4.获得应答码(ftp.getReplyCode)并判断是不是有意义的应答码(230),错误的(登陆信息不正确出现530错误码;如果连接url不正确报连接超时;port不正确直接抛异常connection refused);5如果是没有意义的(关闭连接,返回false)6如果应答有意义,更改连接路径即远程FTP服务器,ftp.listFiles();得到文件集合,并且遍历和要下载的文件名相同的,生成输出流,写到要下载到的某地;

public static boolean download(String url,int port, String username,String password,String remotePath,String fileName,String localPath){

boolean success = false;

FTPClient ftp = new FTPClient();

try{

int reply;

ftp.connect(url,port);

ftp.login(username,password);

reply = ftp.getReplyCode();

if(!FTPReply.ispositiveCompletion(reply)){

ftp.disconnet();

return success;

}

ftp.changeWorkingDirectory(remotePath);

File[] files = ftp.listFiles();

for(File file : files){

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

File f = new File(localPath+”/”+filename);

OutputStream output = new FileOutputStream(f);

ftp.retrieveFile(file.getName(), output);

output.close();

}

}

ftp.logout();

success = true;

}

return success;

}

参考:http://blog.csdn.net/hbcui1984/article/details/2720204

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值