我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
当前回答
是的,您可以使用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));
}
});
}
}
}
其他回答
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);
我不喜欢java.io.File.renameTo(…),因为有时它不重命名文件,你不知道为什么!它只返回true (false)如果失败,它不会抛出异常。
另一方面,java.nio.file.Files.move(…)更有用,因为它会在失败时抛出异常。
如果只是重命名文件,可以使用file . renameto()。
如果您希望将第二个文件的内容附加到第一个文件,请使用附加构造函数选项查看FileOutputStream或FileWriter。您需要读取文件的内容来追加,并使用输出流/写入器将它们写出来。
Files.move(file.toPath(), fileNew.toPath());
工作,但只有当你关闭(或自动关闭)所有使用的资源(InputStream, FileOutputStream等),我认为文件的情况相同。renameTo或FileUtils.moveFile。
简而言之:
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);