今天被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 directoryString 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 fileString 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 InputStreamFile 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 OutputStreamFile 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 servertry {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文件名失败原因相关推荐

  1. java代码ftp重命名未生效_java使用apache commons连接ftp修改ftp文件名失败原因

    今天被ftp上中文名修改坑了好久 项目用的是 apache commons 里的 FtpClient 实现的对ftp文件的上传下载操作,今天增加了业务要修改ftp上的文件名,然后就一直的报错,问题是它 ...

  2. java 用Apache Commons Email发邮件

    所需jar包:commons-email-1.4.jar和mail-1.4.1jar SimpleEmail 用于发送普通文本邮件 package liu.email;import org.apach ...

  3. 阿里云 Java发布SpringBoot项目,使用邮件服务发送失败原因整理

    查了很多失败原因大致有一下几点: 使用了25端口,阿里云默认是禁用掉25端口的,看看能否通 解决办法:代码配置中指定为465端口 telnet smtp.163.com 25 2.使用465端口,依旧 ...

  4. iOS GoldRaccoon第三方FTP文件夹下载失败原因

    一.问题描述:1.下载失败报错: 文件写入失败Error Domain=NSCocoaErrorDomain Code=512 "未能将文件"jquery_1_10_2_min.j ...

  5. 刚从今日头条Java研发岗面试回来,我总结的失败原因(附面试题

    面试岗位: ========= 后端研发工程师 找牛客大佬要了白金码,跳过死亡笔试,直接视频面,从3点开始,到晚上8点结束. 每个面试官给我的感觉都是怎么这么高冷啊. 一面: ======= 写一个题 ...

  6. 刚从今日头条Java研发岗面试回来,我总结的失败原因(附面试题)

    面试岗位: 后端研发工程师 找牛客大佬要了白金码,跳过死亡笔试,直接视频面,从3点开始,到晚上8点结束. 每个面试官给我的感觉都是怎么这么高冷啊. 一面: 写一个题,找一个无序数组的中位数 写了个快排 ...

  7. 错误: java.lang.ClassNotFoundException: org.apache.commons.lang3.StringUtils

    做项目的时候,实现图片异步上传并返回json数据,但是图片上传成功,json数据没有返回,报错:  java.lang.ClassNotFoundException: org.apache.commo ...

  8. 初识 Apache Commons jar 包

    长篇预警 ,要有耐心才能看下去 1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默默无闻的.在我看来,成功而默默无闻的那些框架值得我们格外 ...

  9. 从零开始玩转JMX(四)——Apache Commons Modeler Dynamic MBean

    欢迎支持笔者新作:<深入理解Kafka:核心设计与实践原理>和<RabbitMQ实战指南>,同时欢迎关注笔者的微信公众号:朱小厮的博客. 欢迎跳转到本文的原文链接:https: ...

  10. Apache Commons ArrayUtils.toString(Object)与JDK Arrays.toString(Object)

    Apache Commons Lang提供了一个ArrayUtils类,其中包含toString(Object)方法,该方法"将数组作为字符串输出". 在本文中,我将研究当JDK提 ...

最新文章

  1. 安装oracle11g client 【INS-30131】执行安装程序验证所需的初始设置失败的解决方法
  2. 注解方式使用 Redis 缓存
  3. php接口异常,api接口异常怎么办
  4. 一些移动端开发的细节记录
  5. Django+Jquery+Ajax+验证码登录案例
  6. mysql 改表面_CSS表面(outline)是什么【html5教程】,CSS
  7. MyBatis源码分析(三):MyBatis初始化(配置文件读取和解析)
  8. 使用SQL2005 递归查询结合Row_Number()实现完全SQL端树排序
  9. python降序排列说true不存在_【图片】Python3萌新入门笔记(8)【python吧】_百度贴吧...
  10. win7计算机不显示摄像头图标不见了,win7系统摄像头图标不显示的解决方法
  11. 三维激光雷达点云处理分类及目标检测综述
  12. sql服务器字段顺序怎么修改,你可能不知道SQL Server索引列的升序和降序带来的性能问题...
  13. C语言:getchar( ) 函数详解
  14. 【SeedLab】Packet Sniffing and Spoofing Lab
  15. uc浏览器设置里面的的浏览器ua是什么意思
  16. VBA代码实例---Msgbox函数及应用实例
  17. sdhc卡文件丢失常见原因和两种恢复方法
  18. 计算机组成原理—储存器的层次结构
  19. GitHub忘记用户名和密码如何找回
  20. linux进程间通信(IPC) ---无名管道

热门文章

  1. android jni 结构体_中高级安卓开发技术!Android开发核心知识笔记共2100页,完整版开放下载...
  2. css3中的border-image用法
  3. js页面滚动时层智能浮动定位实现(jQuery/MooTools)
  4. Windows XP Embedded 官方下载地址
  5. python 安装第三方库,超时报错--Read timed out.
  6. 诡异的dp(凸多边形分割):catalan数
  7. wdlinux LAMP
  8. iOS 新浪微博-5.3 首页微博列表_集成图片浏览器
  9. 将对象绑定到WinForm中的combobox时出现的奇怪错误:组合框的下拉项太多!
  10. 登陆模块防止恶意用户SQL注入攻击