1

The question says it all. I have a File object which is pointing to /home/user/filename1.

If I call file.getAbsolutePath() then it would return /home/user/filename1

My question is that -

  1. Can we change the path inside file object to a different location?
  2. If yes, then how?

Thanks

Arunkumar
  • 3,812
  • 3
  • 22
  • 30
  • Reason being, that I am developing it for a cross platform system, where the file names could be case sensitive (for Linux) and case insensitive (for Windows i.e. Fat filesystem). I have been asked to do a case insensitive check on File.exists(), which I have been able to, but I would like the original File object to point to the actual path on system, with its exact case. – Arunkumar Dec 05 '13 at 09:06
  • Why the downvote?? I have clearly asked my doubt whether we can change the path of File. Whats wrong in asking doubts? – Arunkumar Dec 05 '13 at 09:08
  • i am not responsible for that – shreyansh jogi Dec 05 '13 at 09:09
  • maybe people downvoted because they think you could have done more research by yourself, as the fact that File is immutable is not that hard to find out. I did not downvote though, I think the question fits SO – LionC Dec 05 '13 at 09:22

4 Answers4

9

"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "

From the File javadoc.

Blub
  • 3,762
  • 1
  • 13
  • 24
1

I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.

File oldfile =new File(file.getAbsolutePath());
    String origPath = file.getCanonicalPath();
    String destPath = origPath.replace(file.getName(),"");
    String destFile = file.getName();
    String n_destFile = destFile.replace("-a", "");
    File newfile =new File(destPath+n_destFile);
Manoj Krishna
  • 347
  • 1
  • 4
  • 12
0

A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?

Thijser
  • 2,625
  • 1
  • 36
  • 71
0

As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.

Have a look at Apache Commons IO

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

Here you have a useful library to deal with files.

Jorge_B
  • 9,712
  • 2
  • 17
  • 22