溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Java中使用apache ftp工具實現文件上傳下載和刪除功能

發布時間:2021-05-12 17:35:27 來源:億速云 閱讀:165 作者:Leah 欄目:編程語言

這篇文章給大家介紹怎么在Java中使用apache ftp工具實現文件上傳下載和刪除功能,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

1、下載相應的jar包

     commons-net-1.4.1.jar

2、實現代碼如下:

public class FtpUtils { 
    //ftp服務器地址 
    public String hostname = "192.168.1.249"; 
    //ftp服務器端口號默認為21 
    public Integer port = 21 ; 
    //ftp登錄賬號 
    public String username = "root"; 
    //ftp登錄密碼 
    public String password = "123"; 
     
    public FTPClient ftpClient = null; 
     
    /** 
     * 初始化ftp服務器 
     */ 
    public void initFtpClient() { 
      ftpClient = new FTPClient(); 
      ftpClient.setControlEncoding("utf-8"); 
      try { 
        System.out.println("connecting...ftp服務器:"+this.hostname+":"+this.port);  
        ftpClient.connect(hostname, port); //連接ftp服務器 
        ftpClient.login(username, password); //登錄ftp服務器 
        int replyCode = ftpClient.getReplyCode(); //是否成功登錄服務器 
        if(!FTPReply.isPositiveCompletion(replyCode)){ 
          System.out.println("connect failed...ftp服務器:"+this.hostname+":"+this.port);  
        } 
        System.out.println("connect successfu...ftp服務器:"+this.hostname+":"+this.port);  
      }catch (MalformedURLException e) {  
        e.printStackTrace();  
      }catch (IOException e) {  
        e.printStackTrace();  
      }  
    } 
 
    /** 
    * 上傳文件 
    * @param pathname ftp服務保存地址 
    * @param fileName 上傳到ftp的文件名 
    * @param originfilename 待上傳文件的名稱(絕對地址) * 
    * @return 
    */ 
    public boolean uploadFile( String pathname, String fileName,String originfilename){ 
      boolean flag = false; 
      InputStream inputStream = null; 
      try{ 
        System.out.println("開始上傳文件"); 
        inputStream = new FileInputStream(new File(originfilename)); 
        initFtpClient(); 
        ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE); 
        CreateDirecroty(pathname); 
        ftpClient.makeDirectory(pathname); 
        ftpClient.changeWorkingDirectory(pathname); 
        ftpClient.storeFile(fileName, inputStream); 
        inputStream.close(); 
        ftpClient.logout(); 
        flag = true; 
        System.out.println("上傳文件成功"); 
      }catch (Exception e) { 
        System.out.println("上傳文件失敗"); 
        e.printStackTrace(); 
      }finally{ 
        if(ftpClient.isConnected()){  
          try{ 
            ftpClient.disconnect(); 
          }catch(IOException e){ 
            e.printStackTrace(); 
          } 
        }  
        if(null != inputStream){ 
          try { 
            inputStream.close(); 
          } catch (IOException e) { 
            e.printStackTrace(); 
          }  
        }  
      } 
      return true; 
    } 
    /** 
     * 上傳文件 
     * @param pathname ftp服務保存地址 
     * @param fileName 上傳到ftp的文件名 
     * @param inputStream 輸入文件流 
     * @return 
     */ 
    public boolean uploadFile( String pathname, String fileName,InputStream inputStream){ 
      boolean flag = false; 
      try{ 
        System.out.println("開始上傳文件"); 
        initFtpClient(); 
        ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE); 
        CreateDirecroty(pathname); 
        ftpClient.makeDirectory(pathname); 
        ftpClient.changeWorkingDirectory(pathname); 
        ftpClient.storeFile(fileName, inputStream); 
        inputStream.close(); 
        ftpClient.logout(); 
        flag = true; 
        System.out.println("上傳文件成功"); 
      }catch (Exception e) { 
        System.out.println("上傳文件失敗"); 
        e.printStackTrace(); 
      }finally{ 
        if(ftpClient.isConnected()){  
          try{ 
            ftpClient.disconnect(); 
          }catch(IOException e){ 
            e.printStackTrace(); 
          } 
        }  
        if(null != inputStream){ 
          try { 
            inputStream.close(); 
          } catch (IOException e) { 
            e.printStackTrace(); 
          }  
        }  
      } 
      return true; 
    } 
    //改變目錄路徑 
     public boolean changeWorkingDirectory(String directory) { 
        boolean flag = true; 
        try { 
          flag = ftpClient.changeWorkingDirectory(directory); 
          if (flag) { 
           System.out.println("進入文件夾" + directory + " 成功!"); 
 
          } else { 
            System.out.println("進入文件夾" + directory + " 失??!開始創建文件夾"); 
          } 
        } catch (IOException ioe) { 
          ioe.printStackTrace(); 
        } 
        return flag; 
      } 
 
    //創建多層目錄文件,如果有ftp服務器已存在該文件,則不創建,如果無,則創建 
    public boolean CreateDirecroty(String remote) throws IOException { 
      boolean success = true; 
      String directory = remote + "/"; 
      // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄 
      if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) { 
        int start = 0; 
        int end = 0; 
        if (directory.startsWith("/")) { 
          start = 1; 
        } else { 
          start = 0; 
        } 
        end = directory.indexOf("/", start); 
        String path = ""; 
        String paths = ""; 
        while (true) { 
          String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1"); 
          path = path + "/" + subDirectory; 
          if (!existFile(path)) { 
            if (makeDirectory(subDirectory)) { 
              changeWorkingDirectory(subDirectory); 
            } else { 
              System.out.println("創建目錄[" + subDirectory + "]失敗"); 
              changeWorkingDirectory(subDirectory); 
            } 
          } else { 
            changeWorkingDirectory(subDirectory); 
          } 
 
          paths = paths + "/" + subDirectory; 
          start = end + 1; 
          end = directory.indexOf("/", start); 
          // 檢查所有目錄是否創建完畢 
          if (end <= start) { 
            break; 
          } 
        } 
      } 
      return success; 
    } 
 
   //判斷ftp服務器文件是否存在   
    public boolean existFile(String path) throws IOException { 
        boolean flag = false; 
        FTPFile[] ftpFileArr = ftpClient.listFiles(path); 
        if (ftpFileArr.length > 0) { 
          flag = true; 
        } 
        return flag; 
      } 
    //創建目錄 
    public boolean makeDirectory(String dir) { 
      boolean flag = true; 
      try { 
        flag = ftpClient.makeDirectory(dir); 
        if (flag) { 
          System.out.println("創建文件夾" + dir + " 成功!"); 
 
        } else { 
          System.out.println("創建文件夾" + dir + " 失??!"); 
        } 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
      return flag; 
    } 
     
    /** * 下載文件 * 
    * @param pathname FTP服務器文件目錄 * 
    * @param filename 文件名稱 * 
    * @param localpath 下載后的文件路徑 * 
    * @return */ 
    public boolean downloadFile(String pathname, String filename, String localpath){  
      boolean flag = false;  
      OutputStream os=null; 
      try {  
        System.out.println("開始下載文件"); 
        initFtpClient(); 
        //切換FTP目錄  
        ftpClient.changeWorkingDirectory(pathname);  
        FTPFile[] ftpFiles = ftpClient.listFiles();  
        for(FTPFile file : ftpFiles){  
          if(filename.equalsIgnoreCase(file.getName())){  
            File localFile = new File(localpath + "/" + file.getName());  
            os = new FileOutputStream(localFile);  
            ftpClient.retrieveFile(file.getName(), os);  
            os.close();  
          }  
        }  
        ftpClient.logout();  
        flag = true;  
        System.out.println("下載文件成功"); 
      } catch (Exception e) {  
        System.out.println("下載文件失敗"); 
        e.printStackTrace();  
      } finally{  
        if(ftpClient.isConnected()){  
          try{ 
            ftpClient.disconnect(); 
          }catch(IOException e){ 
            e.printStackTrace(); 
          } 
        }  
        if(null != os){ 
          try { 
            os.close(); 
          } catch (IOException e) { 
            e.printStackTrace(); 
          }  
        }  
      }  
      return flag;  
    } 
     
    /** * 刪除文件 * 
    * @param pathname FTP服務器保存目錄 * 
    * @param filename 要刪除的文件名稱 * 
    * @return */  
    public boolean deleteFile(String pathname, String filename){  
      boolean flag = false;  
      try {  
        System.out.println("開始刪除文件"); 
        initFtpClient(); 
        //切換FTP目錄  
        ftpClient.changeWorkingDirectory(pathname);  
        ftpClient.dele(filename);  
        ftpClient.logout(); 
        flag = true;  
        System.out.println("刪除文件成功"); 
      } catch (Exception e) {  
        System.out.println("刪除文件失敗"); 
        e.printStackTrace();  
      } finally { 
        if(ftpClient.isConnected()){  
          try{ 
            ftpClient.disconnect(); 
          }catch(IOException e){ 
            e.printStackTrace(); 
          } 
        }  
      } 
      return flag;  
    } 
     
    public static void main(String[] args) { 
      FtpUtils ftp =new FtpUtils();  
      //ftp.uploadFile("ftpFile/data", "123.docx", "E://123.docx"); 
      //ftp.downloadFile("ftpFile/data", "123.docx", "F://"); 
      ftp.deleteFile("ftpFile/data", "123.docx"); 
      System.out.println("ok"); 
    } 
}

java基本數據類型有哪些

Java的基本數據類型分為:1、整數類型,用來表示整數的數據類型。2、浮點類型,用來表示小數的數據類型。3、字符類型,字符類型的關鍵字是“char”。4、布爾類型,是表示邏輯值的基本數據類型。

關于怎么在Java中使用apache ftp工具實現文件上傳下載和刪除功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女