我有一个接受 File 作为参数的函数。我不想为了将字符串数据传递给函数而创建/写入一个新的 File (我没有对文件系统的写访问权)。我应该补充说,String 数据不存在于文件中(所以我不能从文件中读取数据)。
我可以使用 Streams 并将它们“强制转换”为 File 对象吗?
FileReader r = new FileReader(file);
使用文件读取器加载文件,然后将其内容写入字符串缓冲区。
例子
The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.
Java 中的 档案对象是目录或文件的路径表示,而不是文件本身。创建 File对象不需要对文件系统具有写访问权限,只有在打算实际写入文件时才需要(例如使用 FileOutputStream 文件输出流)
File
File类表示文件的“概念”,而不是用于 I/O 的实际句柄。这就是为什么 File类有一个 .exists()方法,来告诉您该文件是否存在。(你怎么会有一个不存在的 File对象?)
.exists()
相比之下,构造一个 new FileInputStream(new File("/my/file"))可以提供一个实际的流来从中读取字节。
new FileInputStream(new File("/my/file"))
通常,当一个方法接受一个文件时,附近会有另一个方法接受一个流。如果情况并非如此,那么 API 的编码就很糟糕。否则,可以使用临时文件,在许多情况下,临时文件通常授予权限。如果它是 applet,你可以 请求书面许可。
举个例子:
try { // Create temp file. File temp = File.createTempFile("pattern", ".suffix"); // Delete temp file when program exits. temp.deleteOnExit(); // Write to temp file BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write("aString"); out.close(); } catch (IOException e) { }
不; 类 File的实例表示文件系统中的路径。因此,只能对文件使用该函数。但是,也许有一个过载,需要一个 InputStream代替?
InputStream