Mridang Agarwalla
Mridang Agarwalla

Reputation: 45018

Change the name of the deepest directory in a File object

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 how 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.

Upvotes: 0

Views: 1360

Answers (6)

usmanali
usmanali

Reputation: 2036

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.

Upvotes: 1

bluish
bluish

Reputation: 27310

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?

Upvotes: 0

Raghuram
Raghuram

Reputation: 52645

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);

Upvotes: 0

Tom
Tom

Reputation: 44821

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");

Upvotes: 2

Tobias
Tobias

Reputation: 7380

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.

Upvotes: 0

Harry Joy
Harry Joy

Reputation: 59660

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.

Upvotes: 0

Related Questions