热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

这篇文章主要介绍了java使用apachecommons连接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文件名失败原因,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!


推荐阅读
  • 微软头条实习生分享深度学习自学指南
    本文介绍了一位微软头条实习生自学深度学习的经验分享,包括学习资源推荐、重要基础知识的学习要点等。作者强调了学好Python和数学基础的重要性,并提供了一些建议。 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 生成对抗式网络GAN及其衍生CGAN、DCGAN、WGAN、LSGAN、BEGAN介绍
    一、GAN原理介绍学习GAN的第一篇论文当然由是IanGoodfellow于2014年发表的GenerativeAdversarialNetworks(论文下载链接arxiv:[h ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • MACElasticsearch安装步骤及验证方法
    本文介绍了MACElasticsearch的安装步骤,包括下载ZIP文件、解压到安装目录、启动服务,并提供了验证启动是否成功的方法。同时,还介绍了安装elasticsearch-head插件的方法,以便于进行查询操作。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
author-avatar
赞达人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有