9

Java class File has 4 constructors:

  • File(File parent, String child)
    Creates a new File instance from a parent abstract pathname and a child pathname string.

  • File(String pathname)
    Creates a new File instance by converting the given pathname string into an abstract pathname.

  • File(String parent, String child)
    Creates a new File instance from a parent pathname string and a child pathname string.

  • File(URI uri) Creates a new File instance by converting the given file: URI into an abstract pathname.

When I do:

File f=new File("myfile.txt");

Does a physical file on disk get created? Or does JVM make call to OS or does this only create an object inside JVM?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
user710818
  • 23,228
  • 58
  • 149
  • 207
  • 2
    Consider the code new File("myfile.txt").exists(). Could this line return false, if a physical file is created when you do new File? – hakon Sep 02 '11 at 06:32
  • 1
    hakon - Sure it could - if someone between new File() and exists() deleted the file. – Ingo Sep 02 '11 at 09:19

1 Answers1

9

No, creating a new File object does not create a file on the file system. In particular, you can create File objects which refer to paths (and even drives on Windows) which don't exist.

The constructors do ask the underlying file system representation to perform some sort of normalization operations if possible, but this doesn't require the file to be present. As an example of the normalization, consider this code running on Windows:

File f = new File("c:\\a/b\\c/d.txt");
System.out.println(f);

This prints

c:\a\b\c\d.txt

showing that the forward slashes have been normalized to backslashes - but the a, b, and c directories don't actually exist. I believe the normalization is more to do with the operating system naming scheme rather than any actual resources - I don't believe it even looks on disk to see if the file exists.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • also when I call getName() doesn't touch any outside JVM? – user710818 Sep 02 '11 at 06:26
  • @user710818: for this you can check the source (your JDK comes with a `src.zip` which contains the source of most Java classes). In this case: no, it's a getter that does some `String` manipulation, but no native method access (i.e. no calls outside the JVM). – Joachim Sauer Sep 02 '11 at 06:32
  • @user710818...No, getName() too does not touch the file system. It just returns the name as a String. http://download.oracle.com/javase/6/docs/api/java/io/File.html#getName%28%29 – Swaranga Sarma Sep 02 '11 at 06:34