我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
当前回答
这是一个简单的重命名文件的方法:
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");
}
其他回答
试试这个
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
注意: 我们应该总是检查renameTo返回值,以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),如果重命名失败,它不会抛出IO异常。
据我所知,重命名文件不会将其内容附加到具有目标名称的现有文件中。
关于在Java中重命名文件,请参阅file类中renameTo()方法的文档。
您希望在File对象上使用renameTo方法。
首先,创建一个File对象来表示目的地。检查该文件是否存在。如果它不存在,为要移动的文件创建一个新的File对象。在要移动的文件上调用renameTo方法,并检查renameTo的返回值,以查看调用是否成功。
如果要将一个文件的内容附加到另一个文件,有许多可用的写入器。基于扩展,它听起来像是纯文本,所以我会看看FileWriter。
摘自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*/);
运行代码在这里。
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();
}
}
}