java - 如何在Windows的同一目录中复制给定不同名称的文件
问题描述
我一直在尝试复制一个文件,但在同一个 Windows 目录中更改它的名称,但我没有运气。
我不能只复制同一目录中的文件,因为 Windows 规则两个文件不能在同一目录中具有相同的名称。
我不允许将其复制到另一个目录然后重命名它,然后将其移回同一目录中。
而且我在File.class
.
尝试过类似的方法,但没有奏效:
File file = new File(filePath);
File copiedFile = new File(filePath);
//then rename the copiedFile and then try to copy it
Files.copy(file, copiedFile);
解决方案
您可以在同一目录中创建一个新文件,然后将原始文件的内容复制到副本请参阅:Java read from one file and write into another file using methods 了解更多信息
您还可以使用https://www.journaldev.com/861/java-copy-file中的此代码段
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
推荐阅读
- angular - 关闭对话框时如何摆脱未定义的错误?
- flutter - 如何防止键盘在颤动的网页视图中弹出
- javascript - 如何将 async-await 置于循环中?不工作
- angular - 检查来自 API 端点的数据是否已更改(来自 Angular 前端)
- php - Laravel snappy 错误代码 1073741819 - 加载页面 1/6
- python-3.x - Python3如何实现十六进制长除法?
- azure-cosmosdb - Azure Document DB – 带有服务器端 API 的 JS 文件
- node.js - 如何只查看特定用户创建的特定用户,而不查看任何其他信息?
- apex - 删除 Lightning 组件的 CMP 文件时出现问题
- shell - chmod:警告:无法更改 .folder