如何java实现ftp,Java实现FTP相关操作

/**

* Created by 刘万祥 on 2016/4/29.

*

*/

public class FtpTool {

/*ftp用户名*/

private String userName;

/*ftp密码*/

private String password;

/*ftp服务器ip*/

private String ip;

private FTPClient ftpClient;

public FtpTool(String userName, String password, String ip){

this.userName = userName;

this.password = password;

this.ip = ip;

}

/**

* 上传文件

*

* @param  f 要上传的文件

* @param  uploadDir 上传文件的路径

*

* @return boolean b 上传结果

* */

public boolean putFile(File f,String uploadDir) {

InputStream instream = null;

boolean result = false;

try{

try{

ftpClient.changeWorkingDirectory(uploadDir);

instream = new BufferedInputStream(new FileInputStream(f));

result = ftpClient.storeFile(f.getName(), instream);

}finally{

if(instream!=null){

instream.close();

}

}

}catch(IOException e){

e.printStackTrace();

}

return result;

}

/**

* 从ftp服务器下载文件

*

* @param  f 要获取的ftp服务器上的文件

* @param  localPath 本地存放的路径

*

* @return boolean 文件下载是否成功

* */

public boolean getFile(File f  , String localPath){

OutputStream outStream = null;

boolean result = false;

try{

try{

outStream = new BufferedOutputStream(new FileOutputStream(new File(localPath)));

String path = f.getPath();

path = path.replaceAll("\\\\", "/");

String filepath = path.substring(0, path.lastIndexOf("/")+1)+"";

String fileName = path.substring(path.lastIndexOf("/")+1)+"";

boolean b = ftpClient.changeWorkingDirectory(filepath);

if(b){

result = ftpClient.retrieveFile(fileName, outStream);

}

}finally{

if(outStream != null){

outStream.close();

}

}

}catch(IOException e){

e.printStackTrace();

}

return result;

}

/**

* 获取ftp链接

*

* @return ftpClient

* */

public FTPClient getFTPClient(){

try {

ftpClient = new FTPClient();

ftpClient.connect(ip);

ftpClient.login(userName, password);

} catch (SocketException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return ftpClient;

}

/**

*  关闭ftpClient链接

*

*  @param ftpClient 要关闭的ftpClient对象

*

* */

public void closeFTPClient(FTPClient ftpClient){

try {

try{

ftpClient.logout();

}finally{

ftpClient.disconnect();

}

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

FtpTool test=new FtpTool("liuwx","123","127.0.0.1");

FTPClient   client= test.getFTPClient();

System.out.println(client.isAvailable());

System.out.println(client.isConnected());

//        File    file=new File("D:/160429.txt");

//        boolean flag= test.putFile(file,"/");

//        System.out.println(flag);

//        System.out.println(test.getFile(new File("160429.txt"), "D:/123/160429.txt"));

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值