FtpClient FTP操作工具类

来源:互联网 发布:天龙八部刷元宝软件 编辑:程序博客网 时间:2024/05/04 10:04

基于SUN的sun.net.ftp.FtpClient实现文件操作:

1 登录和登出

public void login(String host, String user, String password) {
        try {
                ftpClient.closeServer();
                ftpClient.openServer(host,21);
                ftpClient.login(user, password);
        } catch (Exception e) {
               e.printStackTrace();
        }
 }
 public void logout() {
        try {
               ftpClient.closeServer();
        } catch (IOException e) {
              e.printStackTrace();
        }
}

2 检测FTP是否可用

public boolean isServerAvailable(){
        return (ftpClient.serverIsOpen()?true:false) ;
}

3 从FTP上下载文件

首先需要登陆,操作完成后登出;操作如下:

public void download(String localPath, String remoteFile,String mode) throws FileNotFoundException,IOException{
//mode:指定传输格式为ASCII还是BINARY
       if(mode.equalsIgnoreCase(FTPTransferType_BINARY)){//FTPTransferType_BINARY定义在类里的常量
               ftpClient.binary();
       }else if(mode.equalsIgnoreCase(FTPTransferType_ASCII)){//FTPTransferType_ASCII定义在类里的常量
               ftpClient.ascii();
       }else{
               System.out.println("Unknown transfer type: " + mode);
       }
   
       File file = new File(localPath);//本地文件储存路径
       java.io.InputStream in = ftpClient.get(remoteFile);//FTP目录文件路径
       BufferedOutputStream  out = new BufferedOutputStream (new FileOutputStream(file));
       int r = 0;
       while ((r = in.read()) != -1) {
             out.write(r);
       }
       in.close();
       out.close();
 }

4 上传文件

 public void put(String localPath, String remoteFile,String mode) throws FileNotFoundException,IOException{
         if(mode.equalsIgnoreCase(FTPTransferType_BINARY)){
                  ftpClient.binary();
         }else if(mode.equalsIgnoreCase(FTPTransferType_ASCII)){
                  ftpClient.ascii();
         }else{
                 System.out.println("Unknown transfer type: " + mode);
                 return;
         }
         File file = new File(localPath);
         TelnetOutputStream telnetout = ftpClient.put(remoteFile);
         BufferedOutputStream out = new BufferedOutputStream(telnetout);
         FileInputStream in = new FileInputStream(file);
         int c = 0;
         while ((c = in.read()) != -1) {
                out.write(c);
         }
         in.close();
         out.close(); 
 } 

5  删除文件

public void delete(String filename) throws IOException, FileNotFoundException{

        FtpClient.sendServer("DELE   "+filename) ;

}

原创粉丝点击