使用 Java 重命名文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1158777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:22:01  来源:igfitidea点击:

Rename a file using Java

javafilerenamefile-rename

提问by

Can we rename a file say test.txtto test1.txt?

我们可以重命名一个文件 say test.txttotest1.txt吗?

If test1.txtexists will it rename ?

如果test1.txt存在,它会重命名吗?

How do I rename it to the already existing test1.txt file so the new contents of test.txt are added to it for later use?

如何将其重命名为已经存在的 test1.txt 文件,以便将 test.txt 的新内容添加到其中以供以后使用?

回答by Yuval

As far as I know, renaming a file will not append its contents to that of an existing file with the target name.

据我所知,重命名文件不会将其内容附加到具有目标名称的现有文件的内容。

About renaming a file in Java, see the documentationfor the renameTo()method in class File.

关于重命名Java中的文件,请参阅该文档renameTo()类方法File

回答by Thomas Owens

You want to utilize the renameTomethod on a Fileobject.

您想在File对象上使用renameTo方法。

First, create a File object to represent the destination. Check to see if that file exists. If it doesn't exist, create a new File object for the file to be moved. call the renameTo method on the file to be moved, and check the returned value from renameTo to see if the call was successful.

首先,创建一个 File 对象来表示目的地。检查该文件是否存在。如果它不存在,则为要移动的文件创建一个新的 File 对象。对要移动的文件调用renameTo方法,检查renameTo返回的值,看调用是否成功。

If you want to append the contents of one file to another, there are a number of writers available. Based on the extension, it sounds like it's plain text, so I would look at the FileWriter.

如果您想将一个文件的内容附加到另一个文件,可以使用多种编写器。根据扩展名,它听起来像是纯文本,所以我会看看FileWriter

回答by Pierre

Copied from http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

复制自http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

// File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

if (file2.exists())
   throw new java.io.IOException("file exists");

// Rename file (or directory)
boolean success = file.renameTo(file2);

if (!success) {
   // File was not successfully renamed
}

To append to the new file:

要附加到新文件:

java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);

回答by Dan Vinton

If it's just renaming the file, you can use File.renameTo().

如果只是重命名文件,则可以使用File.renameTo()

In the case where you want to append the contents of the second file to the first, take a look at FileOutputStream with the append constructor optionor The same thing for FileWriter. You'll need to read the contents of the file to append and write them out using the output stream/writer.

如果您想将第二个文件的内容附加到第一个文件,请查看带有附加构造函数选项的 FileOutputStreamFileWriter 的相同内容。您需要读取文件的内容以使用输出流/写入器附加和写出它们。

回答by Brandon

Renaming the file by moving it to a new name. (FileUtils is from Apache Commons IO lib)

通过将文件移动到新名称来重命名文件。(FileUtils 来自 Apache Commons IO 库)

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }

回答by Zoltán

For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's Files.move.

对于 Java 1.6 及更低版本,我认为最安全、最干净的 API 是 Guava 的Files.move

Example:

例子:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

The first line makes sure that the location of the new file is the same directory, i.e. the parent directoryof the old file.

第一行确保新文件的位置是同一个目录,即旧文件的 父目录

EDIT:I wrote this before I started using Java 7, which introduced a very similar approach. So if you're using Java 7+, you should see and upvote kr37's answer.

编辑:我在开始使用 Java 7 之前写了这个,它引入了一种非常相似的方法。因此,如果您使用的是 Java 7+,您应该看到并赞成 kr37 的答案。

回答by kr37

In short:

简而言之:

Files.move(source, source.resolveSibling("newname"));

More detail:

更多详情:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

The following is copied directly from http://docs.oracle.com/javase/7/docs/api/index.html:

以下是直接从http://docs.oracle.com/javase/7/docs/api/index.html复制的:

Suppose we want to rename a file to "newname", keeping the file in the same directory:

假设我们想将一个文件重命名为“newname”,并将文件保存在同一目录中:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

Alternatively, suppose we want to move a file to new directory, keeping the same file name, and replacing any existing file of that name in the directory:

或者,假设我们要将文件移动到新目录,保持相同的文件名,并替换目录中该名称的任何现有文件:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), REPLACE_EXISTING);

回答by senior

This is an easy way to rename a file:

这是重命名文件的简单方法:

        File oldfile =new File("test.txt");
        File newfile =new File("test1.txt");

        if(oldfile.renameTo(newfile)){
            System.out.println("File renamed");
        }else{
            System.out.println("Sorry! the file can't be renamed");
        }

回答by Kirill Ch

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;

Path yourFile = Paths.get("path_to_your_file\text.txt");

Files.move(yourFile, yourFile.resolveSibling("text1.txt"));

To replace an existing file with the name "text1.txt":

用名称“text1.txt”替换现有文件:

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);

回答by Zhurov Konstantin

Files.move(file.toPath(), fileNew.toPath()); 

works, but only when you close (or autoclose) ALL used resources (InputStream, FileOutputStreametc.) I think the same situation with file.renameToor FileUtils.moveFile.

作品,但只有当你接近(或自动关闭)所有使用的资源(InputStreamFileOutputStream等等),我想用同样的情况 file.renameToFileUtils.moveFile