最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java使用apache commons連接ftp修改ftp文件名失敗原因

 更新時間:2019年08月16日 11:22:43   作者:朋也  
這篇文章主要介紹了java使用apache commons連接ftp修改ftp文件名失敗原因解析,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下

今天被ftp上中文名修改坑了好久

項(xiàng)目用的是 apache commons 里的 FtpClient 實(shí)現(xiàn)的對ftp文件的上傳下載操作,今天增加了業(yè)務(wù)要修改ftp上的文件名,然后就一直的報錯,問題是它修改名字的方法只返回一個boolean,沒有異常,這就很蛋疼了,找了好久才發(fā)現(xiàn)是中文的名字的原因

改名

直接上代碼

package net.codejava.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
public class FTPRenamer {
  public static void main(String[] args) {
    String server = "www.ftpserver.com";
    int port = 21;
    String user = "username";
    String pass = "password";
    FTPClient ftpClient = new FTPClient();
    try {
      ftpClient.connect(server, port);
      ftpClient.login(user, pass);
      // renaming directory
      String oldDir = "/photo";
      String newDir = "/photo_2012";
      boolean success = ftpClient.rename(oldDir, newDir);
      if (success) {
        System.out.println(oldDir + " was successfully renamed to: "
            + newDir);
      } else {
        System.out.println("Failed to rename: " + oldDir);
      }
      // renaming file
      String oldFile = "/work/error.png";
      String newFile = "/work/screenshot.png";
      success = ftpClient.rename(oldFile, newFile);
      if (success) {
        System.out.println(oldFile + " was successfully renamed to: "
            + newFile);
      } else {
        System.out.println("Failed to rename: " + oldFile);
      }
      ftpClient.logout();
      ftpClient.disconnect();
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (ftpClient.isConnected()) {
        try {
          ftpClient.logout();
          ftpClient.disconnect();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}
如果修改的名字里沒有中文,用上面的代碼就夠了,但如果有中文就要對文件名進(jìn)行轉(zhuǎn)碼了,轉(zhuǎn)碼代碼如下
// renaming file
String oldFile = "/work/你好.png";
String newFile = "/work/世界.png";
success = ftpClient.rename(
  new String(oldFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1),
  new String(newFile.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)
);

這樣再修改名字就沒有問題了

順便記錄一下上傳、下載、刪除、檢查文件是否存在, 同樣的,如果有中文名,最好先轉(zhuǎn)一下碼再進(jìn)行操作

上傳

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
/**
 * A program that demonstrates how to upload files from local computer
 * to a remote FTP server using Apache Commons Net API.
 * @author www.codejava.net
 */
public class FTPUploadFileDemo {
  public static void main(String[] args) {
    String server = "www.myserver.com";
    int port = 21;
    String user = "user";
    String pass = "pass";
    FTPClient ftpClient = new FTPClient();
    try {
      ftpClient.connect(server, port);
      ftpClient.login(user, pass);
      ftpClient.enterLocalPassiveMode();
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
      // APPROACH #1: uploads first file using an InputStream
      File firstLocalFile = new File("D:/Test/Projects.zip");
      String firstRemoteFile = "Projects.zip";
      InputStream inputStream = new FileInputStream(firstLocalFile);
      System.out.println("Start uploading first file");
      boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
      inputStream.close();
      if (done) {
        System.out.println("The first file is uploaded successfully.");
      }
      // APPROACH #2: uploads second file using an OutputStream
      File secondLocalFile = new File("E:/Test/Report.doc");
      String secondRemoteFile = "test/Report.doc";
      inputStream = new FileInputStream(secondLocalFile);
      System.out.println("Start uploading second file");
      OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
      byte[] bytesIn = new byte[4096];
      int read = 0;
      while ((read = inputStream.read(bytesIn)) != -1) {
        outputStream.write(bytesIn, 0, read);
      }
      inputStream.close();
      outputStream.close();
      boolean completed = ftpClient.completePendingCommand();
      if (completed) {
        System.out.println("The second file is uploaded successfully.");
      }
    } catch (IOException ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      try {
        if (ftpClient.isConnected()) {
          ftpClient.logout();
          ftpClient.disconnect();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

下載

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
/**
 * A program demonstrates how to upload files from local computer to a remote
 * FTP server using Apache Commons Net API.
 * @author www.codejava.net
 */
public class FTPDownloadFileDemo {
  public static void main(String[] args) {
    String server = "www.myserver.com";
    int port = 21;
    String user = "user";
    String pass = "pass";
    FTPClient ftpClient = new FTPClient();
    try {
      ftpClient.connect(server, port);
      ftpClient.login(user, pass);
      ftpClient.enterLocalPassiveMode();
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
      // APPROACH #1: using retrieveFile(String, OutputStream)
      String remoteFile1 = "/test/video.mp4";
      File downloadFile1 = new File("D:/Downloads/video.mp4");
      OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
      boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
      outputStream1.close();
      if (success) {
        System.out.println("File #1 has been downloaded successfully.");
      }
      // APPROACH #2: using InputStream retrieveFileStream(String)
      String remoteFile2 = "/test/song.mp3";
      File downloadFile2 = new File("D:/Downloads/song.mp3");
      OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(downloadFile2));
      InputStream inputStream = ftpClient.retrieveFileStream(remoteFile2);
      byte[] bytesArray = new byte[4096];
      int bytesRead = -1;
      while ((bytesRead = inputStream.read(bytesArray)) != -1) {
        outputStream2.write(bytesArray, 0, bytesRead);
      }
      success = ftpClient.completePendingCommand();
      if (success) {
        System.out.println("File #2 has been downloaded successfully.");
      }
      outputStream2.close();
      inputStream.close();
    } catch (IOException ex) {
      System.out.println("Error: " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      try {
        if (ftpClient.isConnected()) {
          ftpClient.logout();
          ftpClient.disconnect();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

刪除

import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPDeleteFileDemo {
  public static void main(String[] args) {
    String server = "www.myserver.com";
    int port = 21;
    String user = "user";
    String pass = "pass";
    FTPClient ftpClient = new FTPClient();
    try {
      ftpClient.connect(server, port);
      int replyCode = ftpClient.getReplyCode();
      if (!FTPReply.isPositiveCompletion(replyCode)) {
        System.out.println("Connect failed");
        return;
      }
      boolean success = ftpClient.login(user, pass);
      if (!success) {
        System.out.println("Could not login to the server");
        return;
      }
      String fileToDelete = "/repository/video/cool.mp4";
      boolean deleted = ftpClient.deleteFile(fileToDelete);
      if (deleted) {
        System.out.println("The file was deleted successfully.");
      } else {
        System.out.println("Could not delete the file, it may not exist.");
      }
    } catch (IOException ex) {
      System.out.println("Oh no, there was an error: " + ex.getMessage());
      ex.printStackTrace();
    } finally {
      // logs out and disconnects from server
      try {
        if (ftpClient.isConnected()) {
          ftpClient.logout();
          ftpClient.disconnect();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

檢查文件/文件夾是否存在

package net.codejava.ftp;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
 * This program demonstrates how to determine existence of a specific
 * file/directory on a remote FTP server.
 * @author www.codejava.net
 *
 */
public class FTPCheckFileExists {
  private FTPClient ftpClient;
  private int returnCode;
  /**
   * Determines whether a directory exists or not
   * @param dirPath
   * @return true if exists, false otherwise
   * @throws IOException thrown if any I/O error occurred.
   */
  boolean checkDirectoryExists(String dirPath) throws IOException {
    ftpClient.changeWorkingDirectory(dirPath);
    returnCode = ftpClient.getReplyCode();
    if (returnCode == 550) {
      return false;
    }
    return true;
  }
  /**
   * Determines whether a file exists or not
   * @param filePath
   * @return true if exists, false otherwise
   * @throws IOException thrown if any I/O error occurred.
   */
  boolean checkFileExists(String filePath) throws IOException {
    InputStream inputStream = ftpClient.retrieveFileStream(filePath);
    returnCode = ftpClient.getReplyCode();
    if (inputStream == null || returnCode == 550) {
      return false;
    }
    return true;
  }
  /**
   * Connects to a remote FTP server
   */
  void connect(String hostname, int port, String username, String password)
      throws SocketException, IOException {
    ftpClient = new FTPClient();
    ftpClient.connect(hostname, port);
    returnCode = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(returnCode)) {
      throw new IOException("Could not connect");
    }
    boolean loggedIn = ftpClient.login(username, password);
    if (!loggedIn) {
      throw new IOException("Could not login");
    }
    System.out.println("Connected and logged in.");
  }
  /**
   * Logs out and disconnects from the server
   */
  void logout() throws IOException {
    if (ftpClient != null && ftpClient.isConnected()) {
      ftpClient.logout();
      ftpClient.disconnect();
      System.out.println("Logged out");
    }
  }
  /**
   * Runs this program
   */
  public static void main(String[] args) {
    String hostname = "www.yourserver.com";
    int port = 21;
    String username = "your_user";
    String password = "your_password";
    String dirPath = "Photo";
    String filePath = "Music.mp4";
    FTPCheckFileExists ftpApp = new FTPCheckFileExists();
    try {
      ftpApp.connect(hostname, port, username, password);
      boolean exist = ftpApp.checkDirectoryExists(dirPath);
      System.out.println("Is directory " + dirPath + " exists? " + exist);
      exist = ftpApp.checkFileExists(filePath);
      System.out.println("Is file " + filePath + " exists? " + exist);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        ftpApp.logout();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

參考

https://www.codejava.net/java-se/ftp/how-to-start-ftp-programming-with-java

總結(jié)

以上所述是小編給大家介紹的java使用apache commons連接ftp修改ftp文件名失敗原因,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

相關(guān)文章

  • Java內(nèi)存溢出場景及解決方案

    Java內(nèi)存溢出場景及解決方案

    內(nèi)存溢出是Java應(yīng)用開發(fā)中常見的問題,但通過合理的代碼優(yōu)化、內(nèi)存管理以及JVM參數(shù)調(diào)整,我們可以有效地避免和解決這類問題,這篇文章主要介紹了Java內(nèi)存溢出場景及解決辦法,需要的朋友可以參考下
    2024-04-04
  • Java 通過JDBC連接Mysql數(shù)據(jù)庫

    Java 通過JDBC連接Mysql數(shù)據(jù)庫

    本文給大家詳細(xì)介紹了java如何使用JDBC連接Mysql的方法以及驅(qū)動包的安裝,最后給大家附上了java通過JDBC連接其他各種數(shù)據(jù)庫的方法,有需要的小伙伴可以參考下。
    2015-11-11
  • java實(shí)現(xiàn)的漢字轉(zhuǎn)五筆功能實(shí)例

    java實(shí)現(xiàn)的漢字轉(zhuǎn)五筆功能實(shí)例

    這篇文章主要介紹了java實(shí)現(xiàn)的漢字轉(zhuǎn)五筆功能,結(jié)合具體實(shí)例形式分析了java基于字符串遍歷與編碼轉(zhuǎn)換等操作實(shí)現(xiàn)五筆編碼獲取的相關(guān)操作技巧,需要的朋友可以參考下
    2017-06-06
  • 關(guān)于最長遞增子序列問題概述

    關(guān)于最長遞增子序列問題概述

    本文詳細(xì)介紹了最長遞增子序列問題的定義及兩種優(yōu)化解法:貪心+二分查找和動態(tài)規(guī)劃+狀態(tài)壓縮,貪心+二分查找時間復(fù)雜度為O(nlogn),通過維護(hù)一個有序的“尾巴”數(shù)組來高效地找到最長遞增子序列,動態(tài)規(guī)劃+狀態(tài)壓縮則通過狀態(tài)壓縮將空間復(fù)雜度優(yōu)化至O(n)
    2025-02-02
  • 如何將SpringBoot項(xiàng)目打成?war?包并部署到Tomcat

    如何將SpringBoot項(xiàng)目打成?war?包并部署到Tomcat

    這篇文章主要介紹了如何將SpringBoot項(xiàng)目?打成?war?包?并?部署到?Tomcat,當(dāng)前環(huán)境是windows,tomcat版本是8.5采用的springboot版本是2.2.3,本文結(jié)合實(shí)例代碼給大家詳細(xì)講解需要的朋友可以參考下
    2022-11-11
  • 基于Spring接口集成Caffeine+Redis兩級緩存

    基于Spring接口集成Caffeine+Redis兩級緩存

    這篇文章主要介紹了基于Spring接口集成Caffeine+Redis兩級緩存,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-07-07
  • Java中的Optional使用詳細(xì)說明

    Java中的Optional使用詳細(xì)說明

    這篇文章主要介紹了Java中的Optional使用詳細(xì)說明,Optional就是相當(dāng)于把對象包了一層,將判斷空的部分代碼給單獨(dú)抽出來了,主要就是為了避免null引起的部分問題,需要的朋友可以參考下
    2023-11-11
  • Java基礎(chǔ)之八大排序算法

    Java基礎(chǔ)之八大排序算法

    這篇文章主要介紹了Java基礎(chǔ)之八大排序算法,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java基礎(chǔ)的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-04-04
  • Java Builder Pattern建造者模式詳解及實(shí)例

    Java Builder Pattern建造者模式詳解及實(shí)例

    這篇文章主要介紹了Java Builder Pattern建造者模式詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2017-01-01
  • Java 方法引用與ambda表達(dá)式的聯(lián)系

    Java 方法引用與ambda表達(dá)式的聯(lián)系

    這篇文章主要介紹了Java 方法引用與ambda表達(dá)式的聯(lián)系,方法引用通過方法的名字來指向一個方法, 方法引用同樣是Java 8 引入的新特性,而且和Lambda表達(dá)式有著不小的聯(lián)系,它同樣可以根據(jù)上下文進(jìn)行推導(dǎo),進(jìn)而可以簡化代碼
    2022-06-06

最新評論

桐柏县| 深泽县| 富源县| 吉首市| 仙游县| 开封市| 云龙县| 汽车| 东乌珠穆沁旗| 高阳县| 故城县| 伊春市| 新晃| 秦安县| 和硕县| 泸水县| 珠海市| 京山县| 漠河县| 隆德县| 盐源县| 临泉县| 轮台县| 南乐县| 柏乡县| 合山市| 大名县| 南阳市| 门头沟区| 资源县| 丰台区| 博爱县| 家居| 三门峡市| 明光市| 潼关县| 屯留县| 湖口县| 砚山县| 调兵山市| 星子县|