Does the File object create a physical file or touch anything outside of the JVM?

The Java class file has 4 constructors:

  • File(File parent, String child)
    Creates a new file instance from the parent abstract path and the name string of the child path.

  • File(String pathname)
    Creates a new file instance, converting the specified path string to an abstract path.

  • File(String parent, String child)
    Creates a new file instance from the parent path string and the child path name string.

  • File(URI uri) Creates a new file instance, converting the given file: URI to an abstract path.

When I do this:

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

Is a physical file created on disk? Or does the JVM make a call to the OS, or does it only create an object inside the JVM?

+4
source share
1 answer

No, creating a new File object does not create a file in the file system. In particular, you can create File objects that reference paths (and even drives on Windows) that do not exist.

Constructors specify the representation of the base file system, if possible, perform any normalization operations, but this does not require a file. As an example of normalization, consider this code running on Windows:

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

Will print

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

showing that slashes were normalized for backslashes, but the directories a, b, and c do not actually exist. I believe that normalization is more connected with the naming scheme of the operating system, and not with real resources - I do not believe that it even looks at the disk to see if the file exists.

+6
source

All Articles