java实现从ftp服务器上下载文件

最近由于工作上的需要,要实现个从ftp服务器上下载文件的功能。

import java.io.DataInputStream;
import java.io.File;
import java.io.RandomAccessFile;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;

public class FtpClinet {

	public void fileDown() throws Exception{
		TelnetInputStream fget = null;
		RandomAccessFile getFile = null;
		FtpClient fc = null;
		
		String ftpIP = "192.168.1.1";
		String userName = "userName";
		String passWord = "passWord";
		String fileName = "fileName";
		String fileUrl = "fileUrl";
		try {
			int ch;
			if(!new File("d:/mmis/attachment/304_").isDirectory()){//判断本地存放文件的文件夹是否存在
				new File("d:/mmis/attachment/304_").mkdir();
			}
			String keepLocate = "d:/mmis/attachment/304/"+fileName;//
			
			fc = new FtpClient();//ftp客户端对象
			fc.openServer(ftpIP);//连接ftp服务器
			fc.login(userName, passWord);//登录ftp服务器
			fc.binary();//使用二进制的方式下载
			fget=fc.get(fileUrl);//读取ftp远程文件
			DataInputStream puts = new DataInputStream(fget);//			
			File fi = new File(keepLocate);//新建本地文件
			getFile = new RandomAccessFile(fi,"rw");//以读写的方式打开本地文件
			getFile.seek(0); //将指针放到文件最前段
			while ((ch = puts.read()) >= 0) {//循环读取远程文件的内容并写入本地文件中
                getFile.write(ch);
            }
		} catch (Exception e) {
			e.printStackTrace(System.out);
			throw new Exception(e.getMessage());
		}finally{
			try{
				fget.close();
			}catch (Exception e) {}
			try{
				getFile.close();
			}catch (Exception e) {}
			try{
				 fc.closeServer();
			}catch (Exception e) {}
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值