如何在java中重新命名文件

时间:2022-10-03 10:48:09

I want to rename a file name xxx.docx to xxx.docx.zip then rename it back to xxx.docx in Java.

我想将文件名xxx.docx重命名为xxx.docx.zip,然后将其重命名为Java中的xxx.docx。

Here is my code.

这是我的代码。

File file = new File(path);
File file2 = new File(path+".zip");
file.renameTo(file2);
File file3 = new File(file.getPath());
file2.renameTo(file3);

It won't work. Thank you.

它不会起作用。谢谢。

Edit : The problem is I forgot to close the doc before renaming it.

编辑:问题是我忘记在重命名之前关闭文档。

1 个解决方案

#1


The code like that works. Most probably some other process has locked the file and made it read only. You have either opened it in word (since it is docx file) or something like that. Maybe it is in a readonly location.

像这样的代码工作。很可能其他一些进程已锁定文件并使其只读。你已经用word打开了它(因为它是docx文件)或类似的东西。也许它在一个只读位置。

The code is working though. Try with different file and you will see it is fine (I tried it).

代码正在运行。尝试使用不同的文件,你会发现它很好(我试过)。

#1


The code like that works. Most probably some other process has locked the file and made it read only. You have either opened it in word (since it is docx file) or something like that. Maybe it is in a readonly location.

像这样的代码工作。很可能其他一些进程已锁定文件并使其只读。你已经用word打开了它(因为它是docx文件)或类似的东西。也许它在一个只读位置。

The code is working though. Try with different file and you will see it is fine (I tried it).

代码正在运行。尝试使用不同的文件,你会发现它很好(我试过)。