I have File object in Java which is a directory path:
C:\foo\foo\bar
...and I would like to change this to:
C:\foo\foo\newname
I'm don't mean renaming the actual directory, but, simply modifying the path in the File object. Could someone show me ho开发者_如何学JAVAw I can do this? Do I have to use string functions for this or is there some inbuilt Java function that I can use?
Thanks.
You can construct one File from another and get the parent directory of a file, combining these:
File orig = new File("C:\\foo\\foo\\bar");
File other = new File(orig.getParentFile(), "newname");
There is no such method in java that changes path for the File object, however you can get the file path with getPath() or getAbsolutePath(). I think creating a new file at that path would do.
Try following:
import java.io.File;
public class MainClass {
public static void main(String[] a) {
File file = new File("c:\\foo\\foo\\bar");
file.renameTo(new File("c:\\foo\\foo\\newname"));
}
}
Hope this helps.
You can use the string-representation of the File object and search for the last / with indexOf(), then you change the value after it and create a new File object.
I guess you need to something like this.
String sourcePath = "C:\\foo\\foo\\bar";
String newName = "newname";
File source = new File(sourcePath);
File dest = new File(source.getParent() + File.separator + newName);
source.renameTo(dest);
I think you can only create a new File
object with the new path:
File f2 = new File("C:\\foo\\foo\\newname")
Does it make any side effect on your code?
精彩评论