java代码ftp重命名未生效_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();
}
}
}
}
参考
总结
以上所述是小编给大家介绍的java使用apache commons连接ftp修改ftp文件名失败原因,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
java代码ftp重命名未生效_java使用apache commons连接ftp修改ftp文件名失败原因相关推荐
- java代码ftp重命名未生效_java实现FTP远程文件移动(重命名、复制、拷贝) | 学步园...
首先就标题说明一点,java使用org.apache.commons.net.ftp.ftpclient包来操作FTP是很爽滴,但对远程文件操作,好像没有实现 复制文件的方法.我用的是文件移动(mov ...
- java文件移动重命名_Java重命名文件和移动文件
Java重命名文件或移动文件是一种常见的IO操作.可以使用File.renameTo(File dest)方法进行重命名文件和移动文件操作. 1. Java重命名文件 如果文件重命名成功,则文件ren ...
- java文件批量重命名6,批量重命名文件DOS脚本
我自己写的一个进行批量文件重命名的批处理文件: rem modify the file name to the regular name echo modifing -- forfiles /s /m ...
- 代码批量重命名图片:去掉图片名字的末尾几个字符
处理9.5万张图片,将它们名字的倒数9位去掉: 原数据集样子: 改名后: 百度了一些软件比如"拖把更名器SRename-v1.98i",由于数据集太多了,这个软件到底能不能用没有实 ...
- Java实现批量重命名文件
package useful; import java.io.File; public class UpdateFileName { public static void main(String[] ...
- Java renameTo 文件重命名
Java 文件重名 package cn.strivepine.util;import java.io.File;/*** @Author StrivePine* @data 2022/5/13 14 ...
- java文件批量重命名文件,文件批量工具(File Attribute Changer)
文件批量工具(File Attribute Changer)是一款对文件属性批量修改,以及对文件批量重命名的工具,所 谓的文件属性是指隐藏属性,在查看磁盘文件的名称时,系统一般不会显示具有隐藏属性的文 ...
- java代码如何写正则汉字规则_JAVA 正则表达式、汉字正则、 java正则代码
1. 只有字母.数字和下划线且不能以下划线开头和结尾的正则表达式:^(?!_)(?!.*?_$)[a-zA-Z0-9_]+$ 只有字母和数字的: ^[a-zA-Z0-9_]+$ 2. 至少一个汉字.数 ...
- java代码没错却运行不了_Java代码没错误,tomcat能正常运行,但是我的项目主页却一直显示不了,显示404错误...
重新在别人的电抄脑上配置一次环境变量bai 配置环境变量 点击du计算机->高级系zhi统设置->环境变量dao-> 在第一个中新建一个 变量:classpath 值:.;(记住是分 ...
最新文章
- 手把手教你用Python实现自动特征工程
- java多线程共享信息_java多线程信息共享
- cent 8.0 安装tomcat 9.0_JDK-TOMCAT-MYSQL安装
- OC语言Block和协议
- C++中关于隐藏的理解
- ssas 层次结构_分析服务(SSAS)多维设计技巧–关系和层次结构
- C++标准库之stack
- 1、Python基本对象类型----数字
- rust原声音乐_Joan Baez – Diamonds Rust
- 计算机组成原理核心总结
- 机器学习、深度学习、计算机视觉、自然语言处理及应用案例
- 一键U盘装系统 电脑内存使用率高的解决方法
- 使用饿了么update组件 实现多文件上传到后台以及本地图片显示功能
- Python深度学习之处理文本数据
- 2021年危险化学品经营单位安全管理人员复审考试及危险化学品经营单位安全管理人员模拟考试
- 图片转DATA:URI工具
- 国内智能视频分析监控技术的出路
- 计算机网络笔记02---网络边缘和网络核心
- android 带头像的弹幕,原生Canvas实现带头像的弹幕
- FPGA课程设计——数字电子时钟VERILOG(基于正点原子新起点开发板,支持8位或6位共阳极数码管显示时分秒毫秒,可校时,可设闹钟,闹钟开关,led指示)
热门文章
- linux咋socket编程,linux中socket编程
- os.path.join拼接错误
- PyTorch框架学习七——自定义transforms方法
- Python面试题大全(一):基础知识学习
- C/C++求一个整数的二进制中1的个数(用三种效率不同的方法实现)
- SpringBoot 自带工具类~ResourceUtils
- MC缓存序列化php,PHP serialize()序列化的使用
- 10停止nginx命令 win_Linux下配置Nginx并使用https协议
- 男人女人小孩共32人c语言,C编程核心要点,你确信你会C语言?看完之后,男人沉默,女人流泪...
- 上古卷轴5json文件修改_【白夜谈】我做了一款失败的《社长卷轴》Mod