创建一个File对象是创建一个物理文件还是触摸JVM之外的任何东西? [英] Does creating a File object create a physical file or touch anything outside the JVM?

查看:264
本文介绍了创建一个File对象是创建一个物理文件还是触摸JVM之外的任何东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java类文件有4个构造函数:


  • 文件(File parent,String child)

    / code>

    从父级抽象路径名和
    a子路径名字符串中创建一个新的File实例。

  • File(String pathname)

    通过将给定的路径名​​字符串
    转换为抽象路径名来创建一个新的File实例。


  • File(String parent,String child)

    从父路径名创建一个新的File实例字符串和
    子路径名字符串。

  • 文件(URI URI)
    通过将给定文件:URI转换为
    抽象路径名创建一个新的File实例。


  • 我做:

      File f = new File(myfile.txt); 

    磁盘上的物理文件是否被创建?或者JVM调用OS还是只在JVM中创建对象?

    解决方案

    不,创建一个新的 File object does not 在文件系统上创建一个文件。特别是,您可以创建 File 对象,它指向不存在的路径(甚至Windows驱动器)。



    构造函数 do 请求底层文件系统表示在可能的情况下执行某种规范化操作,但是 不要求文件存在。作为规范化的一个例子,请考虑在Windows上运行此代码:

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

    打印

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

    显示正斜杠已经被正规化为反斜杠 - 但是a,b和c目录实际上并不存在。我认为标准化更多的是与操作系统命名方案有关,而不是任何实际的资源 - 我不相信它甚至会在磁盘上查看文件是否存在。


    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?

    解决方案

    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.

    这篇关于创建一个File对象是创建一个物理文件还是触摸JVM之外的任何东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆