我们能否将一个名为test.txt
的文件重命名为test1.txt
?
如果test1.txt
已存在,它会被重命名吗?
如何将其重命名为已经存在的test1.txt
文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能否将一个名为test.txt
的文件重命名为test1.txt
?
如果test1.txt
已存在,它会被重命名吗?
如何将其重命名为已经存在的test1.txt
文件,以便将test.txt的新内容添加到其中以供以后使用?
这是我成功重命名文件夹中多个文件的代码:
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");
Files.move(file.toPath(), fileNew.toPath());
这个方法可以起作用,但只有在关闭(或自动关闭)所有使用的资源(InputStream
、FileOutputStream
等)后才能实现。我认为 file.renameTo
或 FileUtils.moveFile
也是同样的情况。
代码已经在此处运行。
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();
}
}
}