Java 写入从 getResourceAsStream() 返回的文件流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2797367/
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
Write to a file stream returned from getResourceAsStream()
提问by Andreas Grech
I am getting a a InputStream
from getResourceAsStream()
, and I managed to read from the file by passing the returned InputStream
to a BufferedReader
.
我得到AAInputStream
的getResourceAsStream()
,我设法通过将返回从文件中读取InputStream
到BufferedReader
。
Is there any way I can write to the file as well?
有什么办法可以写入文件吗?
采纳答案by skaffman
Not directly, no - getResourceAsStream()
is intended to return a view on read-only resources.
不直接,不 -getResourceAsStream()
旨在返回只读资源的视图。
If you know that the resource is a writeable file, though, you can jump through some hoops, e.g.
但是,如果您知道该资源是可写文件,则可以跳过一些问题,例如
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. Try it and find out, though, you might be OK.
这在 Unix 风格的系统上应该可以很好地工作,但 Windows 文件路径可能会导致这种消化不良。尝试一下,然后发现,不过,您可能会没事。
回答by Michael Borgwardt
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. 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.
谁说是文件?重点getResourceAsStream()
是将其抽象化,因为它很可能不是真的。具体来说,资源可以位于 JAR 文件中,可以从 HTTP 服务器读取,或者实际上是实现者ClassLoader
可以想象的任何东西。
You really shouldn't wantto 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 APIor the user's home directory.
你真的不应该要写入的资源这是你的计划分配的一部分。在大多数情况下,从概念上讲,这是错误的做法。设置或特定于用户的数据应转到Preferences API或用户的主目录。