最近由于工作上的需要,要实现个从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) {} } } }相关资源:java实现本地按照FTP服务器上目录结构创建文件夹下载文件