使用 Java 重命名文件

发布于 2024-07-29 12:56:14 字数 181 浏览 3 评论 0 原文

我们可以将文件 test.txt 重命名为 test1.txt 吗?

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

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

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

If test1.txt exists will it rename ?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

記憶穿過時間隧道 2024-08-05 12:56:14

复制自 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
}

附加到新文件:

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

Copied from 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*/);
没︽人懂的悲伤 2024-08-05 12:56:14

简而言之:

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

更多详细信息:

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

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

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

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

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

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

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;
import java.nio.file.StandardCopyOption;

The following is copied directly from 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:

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()), StandardCopyOption.REPLACE_EXISTING);
所谓喜欢 2024-08-05 12:56:14

对于 Java 1.6 及更低版本,我相信最安全、最干净的 API 是 Guava 的 文件.move

示例:

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

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

编辑:
我在开始使用 Java 7 之前写了这篇文章,Java 7 引入了一种非常相似的方法。 因此,如果您使用的是 Java 7+,您应该查看并投票 kr37 的答案。

For Java 1.6 and lower, I believe the safest and cleanest API for this is Guava's 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 directory of 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.

◇流星雨 2024-08-05 12:56:14

您想利用 文件上的 ">renameTo 方法对象。

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

如果您想将一个文件的内容追加到另一个文件中,可以使用多种编写器。 基于扩展名,听起来像是纯文本,所以我会查看 文件写入器

You want to utilize the renameTo method on a File object.

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.

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.

甜扑 2024-08-05 12:56:14

通过将文件移至新名称来重命名该文件。 (FileUtils 来自 Apache Commons IO lib)

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

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

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

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

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }
你怎么敢 2024-08-05 12:56:14

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

        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");
        }

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");
        }
黎歌 2024-08-05 12:56:14
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"));

要将现有文件替换为名称“text1.txt”:

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
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":

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);
递刀给你 2024-08-05 12:56:14

试试这个

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

注意:
我们应该始终检查 renameTo 返回值以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),并且如果重命名失败,它不会抛出 IO 异常。

Try This

File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult

Note :
We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.

伊面 2024-08-05 12:56:14

是的,您可以使用 File.renameTo()。 但请记住在将其重命名为新文件时要有正确的路径。

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

沦落红尘 2024-08-05 12:56:14

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

如果您想将第二个文件的内容附加到第一个文件,请查看 带有附加构造函数选项的 FileOutputStreamFileWriter 也是如此。 您需要读取文件的内容以附加并使用输出流/编写器将其写出。

If it's just renaming the file, you can use 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 option or 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.

撩发小公举 2024-08-05 12:56:14

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

有关在 Java 中重命名文件的信息,请参阅 File 类中的 renameTo() 方法的文档

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 documentation for the renameTo() method in class File.

街角卖回忆 2024-08-05 12:56:14
Files.move(file.toPath(), fileNew.toPath()); 

有效,但仅当您关闭(或自动关闭)所有使用的资源(InputStreamFileOutputStream 等)时我认为与 file.renameTo 的情况相同> 或FileUtils.moveFile

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

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

通知家属抬走 2024-08-05 12:56:14

这是我成功重命名文件夹中的多个文件的代码:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

并运行它作为示例:

renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");

Here is my code to rename multiple files in a folder successfully:

public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
    if(newName == null || newName.equals("")) {
        System.out.println("New name cannot be null or empty");
        return;
    }
    if(extension == null || extension.equals("")) {
        System.out.println("Extension cannot be null or empty");
        return;
    }

    File dir = new File(folderPath);

    int i = 1;
    if (dir.isDirectory()) { // make sure it's a directory
        for (final File f : dir.listFiles()) {
            try {
                File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);

                if(f.renameTo(newfile)){
                    System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
                } else {
                    System.out.println("Rename failed");
                }
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

and run it for an example:

renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
骄兵必败 2024-08-05 12:56:14

我不喜欢 java.io.File.renameTo(...) 因为有时它不会重命名文件,而你不知道为什么! 它只是返回 true 或 false。 如果失败,它不会抛出异常。

另一方面,java.nio.file.Files.move(...) 更有用,因为它在失败时抛出异常。

I do not like java.io.File.renameTo(...) because sometimes it does not rename the file and you do not know why! It just returns true or false. It does not throw an exception if it fails.

On the other hand, java.nio.file.Files.move(...) is more useful as it throws an exception when it fails.

调妓 2024-08-05 12:56:14

file.renameTo(File(file.parent, text))

file.renameTo(File(file.parent, text))

ㄟ。诗瑗 2024-08-05 12:56:14

运行代码在这里。

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Running code is here.

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文