[英]Write to a file stream returned from getResourceAsStream()
I am getting aa InputStream
from getResourceAsStream()
, and I managed to read from the file by passing the returned InputStream
to a BufferedReader
. 我从
getResourceAsStream()
获取一个InputStream
,我设法通过将返回的InputStream
传递给BufferedReader
来读取该文件。
Is there any way I can write to the file as well? 有什么方法可以写入文件吗?
Not directly, no - getResourceAsStream()
is intended to return a view on read-only resources. 不直接,no -
getResourceAsStream()
旨在返回只读资源的视图。
If you know that the resource is a writeable file, though, you can jump through some hoops, eg 但是,如果你知道资源是一个可写文件,你可以跳过一些箍,例如
URL resourceUrl = getClass().getResource(path);
File file = new File(resourceUrl.toURI());
OutputStream output = new FileOutputStream(file);
This should work nicely on unix-style systems, but windows file paths might give this indigestion. 这应该适用于unix风格的系统,但Windows文件路径可能会导致这种消化不良。 Try it and find out, though, you might be OK.
尝试一下,然后找出答案,你可能会好的。
Is there any way I can write to the file as well?
有什么方法可以写入文件吗?
Who says it's a file? 谁说这是一个档案? The whole point of
getResourceAsStream()
is to abstract that away because it might well not be true. getResourceAsStream()
是抽象它,因为它可能不是真的。 Specifically, the resource may be situated in a JAR file, may be read from a HTTP server, or really anything that the implementer of the ClassLoader
could imagine. 具体而言,资源可以位于JAR文件中,可以从HTTP服务器读取,或者实际上是
ClassLoader
的实现者可以想象的任何内容。
You really shouldn't want to write to a resource that's part of your program distribution. 你真的不应该要写入的资源,你的计划分配的一部分。 It's conceptually the wrong thing to do in most cases.
在大多数情况下,这在概念上是错误的。 Settings or User-specific data should go to the Preferences API or the user's home directory.
设置或用户特定数据应该转到Preferences API或用户的主目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.