`
yelr_j
  • 浏览: 66168 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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) {}
		}
	}
}

 

分享到:
评论
3 楼 jianqiangking 2011-06-17  
                
2 楼 jianqiangking 2011-06-17  
请问fileUrl的值怎么写?
1 楼 jianqiangking 2011-06-17  
请问fileUrl 属性的值怎么写?

相关推荐

Global site tag (gtag.js) - Google Analytics