0

Is it okay to make an object of type File, which I later would like to write into, have a final declaration? I'd like to pass it to a Runnable inner class.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user3475234
  • 1,503
  • 3
  • 22
  • 40

4 Answers4

3

final declaration allows you to write/read into, but not change the reference of the object.

final File fileRef = new File("/path/to/my/file.txt");
fileRef = new File("/new/path/to/file"); // illegal
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
2

There is no problem, final doesn't mean that the object itself can't alter its state. It just means that the variable can't be reassigned. So it applies to a different thing.

In addition to this, a File is just an abstract representation of a file system file or folder. You don't write through a File object, you use it to open a stream (eg. FileWriter).

Jack
  • 131,802
  • 30
  • 241
  • 343
2

Yes. Making a variable final means you can't change it to point to a different object. You can totally do whatever you want with the object it does point to, though.

final File file = new File("foo");

Runnable r = new Runnable() {
    public void run() {
        file.renameTo("bar");    // Cool.
        file.delete();           // Cool.
        file = new File("bar");  // Whoa. Not cool.
    }
};
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

An object from File class is an abstract representation of a file or directory from the real hard drive. It is not the physical file or folder.

If you mark the variable as final then it cannot be re assigned. That's all. Marking the variable as final won't make the physical file immutable. If the Runnable is created as an anonymous class and the File variable is local to the method (parameter or local variable), then yes. Otherwise, no.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332