如何在不保存到硬盘的情况下在 Java 中创建 File 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19413153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:56:53  来源:igfitidea点击:

How to create File object in Java without saving to hard disk

javafileio

提问by Alexander Mills

Can you create a File object in Java without saving to hard disk?

您可以在不保存到硬盘的情况下在 Java 中创建 File 对象吗?

All the constructors for java.io.File seem to take info about a location on disk.

java.io.File 的所有构造函数似乎都获取有关磁盘位置的信息。

采纳答案by nanofarad

A Fileobject is not a file. It is a path to a location on disk with some utility methods. This location need not existto have a valid file. For instance, you can do File#createNewFileto create a physical file after creating a Fileobject that would point to that pathname on disk.

一个File对象不是一个文件。它是磁盘上某个位置的路径,具有一些实用方法。此位置不需要存在即可拥有有效文件。例如,您可以File#createNewFile在创建一个File指向磁盘上该路径名的对象后创建一个物理文件。

Use URLand related classes to read remotely, or some sort of java.nio.ByteBufferto store file data in memory.

使用URL和相关的类来远程读取,或某种方式java.nio.ByteBuffer将文件数据存储在内存中。

回答by Claudiu

Even if you create a file object, the file itself does not need to exist on disk.

即使您创建了文件对象,文件本身也不需要存在于磁盘上。

When constructing the java object, you need to specify a location of the file absolute or relative to the current directory, but the file itself does not need to exist on disk.

构造java对象时,需要指定文件相对于当前目录的绝对或相对位置,但文件本身不需要存在于磁盘上。