java使用apache commons连接ftp修改ftp文件名失败原因

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

项目用的是 apache commons 里的 FtpClient 实现的对ftp文件的上传下载操作,今天增加了业务要修改ftp上的文件名,然后就一直的报错,问题是它修改名字的方法只返回一个boolean,没有异常,这就很蛋疼了,找了好久才发现是中文的名字的原因

改名

直接上代码

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();
        }
      }
    }
  }
}
如果修改的名字里没有中文,用上面的代码就够了,但如果有中文就要对文件名进行转码了,转码代码如下
// 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)
);

这样再修改名字就没有问题了

顺便记录一下上传、下载、删除、检查文件是否存在, 同样的,如果有中文名,最好先转一下码再进行操作

上传

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

总结

以上所述是小编给大家介绍的java使用apache commons连接ftp修改ftp文件名失败原因,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

(0)

相关推荐

  • Java 实现FTP服务实例详解

    Java 实现FTP服务实例详解 1.FTP简介 FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件.在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)."

  • java判断ftp目录是否存在的方法

    本文为大家分享了java判断ftp目录是否存在的方法,供大家参考,具体内容如下 package com.soft4j.log4j; import java.io.IOException; import sun.net.ftp.FtpClient; public class FtpTest { static String middle_ftpServer = "10.103.2.250"; static String middle_user = "ora9iftp";

  • 详解JAVA中使用FTPClient工具类上传下载

    详解JAVA中使用FTPClient工具类上传下载 在Java程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件.本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件. 1.写一个javabean文件,描述ftp上传或下载的信息 实例代码: public class FtpUseBean { private String host; private Integer port; private String us

  • java利用Apache commons codec进行MD5加密,BASE64加密解密,执行系统命令

    编写代码之前先来介绍一下我们要用到的两个包; commons-codec-1.10.jar Commons项目中用来处理常用的编码方法的工具类包,例如DES.SHA1.MD5.Base64,URL,Soundx等等. commons-exec-1.3.jar Apache Commons Exec 是 Apache 上的一个 Java 项目,提供一些常用的方法用来执行外部进程 你可以到本站直接下载 Apache Commons 官方包 下面看一下代码结构: import org.apache.c

  • java实现ftp上传 如何创建文件夹

    java如何实现ftp上传?如何创建文件夹? 最佳答案: 准备条件:java实现ftp上传用到了commons-net-3.3.jar包 首先建立ftphost连接 public boolean connect(String path, String addr, int port, String username, String password) { try { //FTPClient ftp = new FTPHTTPClient(addr, port, username, password

  • Java使用FTPClient类读写FTP

    本文实例为大家分享了Java使用FTPClient类读写FTP的具体代码,供大家参考,具体内容如下 1.首先先导入相关jar包 2.创建一个连接FTP的工具类FTPUtil.java package com.metarnet.ftp.util; import java.io.IOException; import java.io.InputStream; import java.net.SocketException; import java.util.Properties; import or

  • java使用apache commons连接ftp修改ftp文件名失败原因

    今天被ftp上中文名修改坑了好久 项目用的是 apache commons 里的 FtpClient 实现的对ftp文件的上传下载操作,今天增加了业务要修改ftp上的文件名,然后就一直的报错,问题是它修改名字的方法只返回一个boolean,没有异常,这就很蛋疼了,找了好久才发现是中文的名字的原因 改名 直接上代码 package net.codejava.ftp; import java.io.IOException; import org.apache.commons.net.ftp.FTPC

  • apache commons工具集代码详解

    Apache Commons包含了很多开源的工具,用于解决平时编程经常会遇到的问题,减少重复劳动.下面是我这几年做开发过程中自己用过的工具类做简单介绍. 组件 功能介绍 BeanUtils 提供了对于JavaBean进行各种操作,克隆对象,属性等等. Betwixt XML与Java对象之间相互转换. Codec 处理常用的编码方法的工具类包 例如DES.SHA1.MD5.Base64等. Collections java集合框架操作. Compress java提供文件打包 压缩类库. Con

  • java基于Apache FTP实现文件上传、下载、修改文件名、删除

    Apache FTP 是应用比较广泛的FTP上传客户端工具,它易于操作,代码简略,结构清晰,是做FTP文件客户端管理软件的优先之选.FTP的操作包括:FTP文件上传(断点续传).FTP文件下载.FTP文件重命名.FTP文件删除,这些操作已经将FTP应用管理的方式发挥的淋漓尽致了,So 我一直都用此种方式来实现FTP文件服务器的管理工作:下附FTP工具代码. 1.FTP文件操作状态枚举类 package com.scengine.wtms.utils.ftp; public enum FTPSta

  • java基于Apache FTP点断续传的文件上传和下载

    基于Apache FTP实现文件上传下载工具 ,上传文件时需要考虑以下问题(实例是续传功能): (1). FTP服务器是否存在改目录,如果不存在目录则需要创建目录. (2).判断上传文件是否已经存在,如果存在是需要删除后再上传还是续传. 1.上传或下载状态的枚举类: package com.scengine.wtms.utils.ftp; public enum UploadStatus { File_Exits(0), Create_Directory_Success(1), Create_D

  • java使用Apache工具集实现ftp文件传输代码详解

    本文主要介绍如何使用Apache工具集commons-net提供的ftp工具实现向ftp服务器上传和下载文件. 一.准备 需要引用commons-net-3.5.jar包. 使用maven导入: <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.5</version> </depend

  • java实现将文件上传到ftp服务器的方法

    本文实例讲述了java实现将文件上传到ftp服务器的方法.分享给大家供大家参考,具体如下: 工具类: package com.fz.common.util; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; imp

  • java实现文件上传下载至ftp服务器

    以前做的一个项目,用到了文件上传下载至ftp服务器,现在对其进行一下复习,比较简单,一下就能看明白. 环境:首先,先安装ftp服务器,我是在win8本地用IIS配置的, 百度一下就可以找到安装文档. 1.在你的项目目录下建立ftp配置文件,目录如下图 01 ftpconfig.properties: ftpIp=10.73.222.29 ftpPort=21 ftpUser=WP ftpPwd=04143114wp ftpRemotePath=d://share 02 读取ftpconfig.p

  • 基于Java手写一个好用的FTP操作工具类

    目录 前言 windows服务器搭建FTP服务 工具类方法 代码展示 使用示例 前言 网上百度了很多FTP的java 工具类,发现文章代码都比较久远,且代码臃肿,即使搜到了代码写的还可以的,封装的常用操作方法不全面,于是自己花了半天实现一个好用的工具类.最初想用java自带的FTPClient 的jar 去封装,后来和apache的jar工具包对比后,发现易用性远不如apache,于是决定采用apache的ftp的jar 封装ftp操作类. windows服务器搭建FTP服务 打开控制版面,图示

  • Java语言实现简单FTP软件 FTP软件本地窗口实现(5)

    本文为大家介绍了FTP软件本地窗口的实现方法,供大家参考,具体内容如下 1.首先看一下本地窗口的布局效果 2.看一下本地窗口实现的代码框架 3.本地窗口的具体实现代码LocalPanel.java package com.oyp.ftp.panel.local; import java.awt.Color; import java.awt.Desktop; import java.awt.Dimension; import java.awt.event.ItemEvent; import jav

随机推荐