I have two File Object oldFile and newFile and I would like to exchange the corresponding file names. So I rename oldFile to a tmpFile name first. I get the oldFile’s absolute path and append “.bak” for it:
String tmpFile = oldFile.getAbsolutePath().toString()+".bak";
oldFile.renameTo(new File(tmpFile));
The problem is that tmpFile contains the raw string of path,while the constructor of File class treat the ‘\’ as the escape.So the tmpFile may be “D:\oldfile.java.bak”,however what the constructor need is
new File("D:\\oldfile.java.bak");
How can I deal with it?
You have to escape the escapes with
.replace("\", "\\")but if you have to do that then realize you don’t have to use\on Windows. Java supports/just as fine and it doesn’t have these problems. You can doreplace("\", "/")and it works just as well.You also need to read and understand how to create new files in Java.
File.createNewFile()is required to be called. Just creating aFileobject with the constructor doesn’t actual create a file on the filesystem nor does it guarantee that a file at that location exists.