Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

jvm

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?

like image 236
user710818 Avatar asked Sep 02 '11 06:09

user710818


1 Answers

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.

like image 151
Jon Skeet Avatar answered Oct 31 '22 22:10

Jon Skeet