Write to a file stream returned from getResourceAsStream()

后端 未结 2 1271
慢半拍i
慢半拍i 2020-12-01 18:08

I am getting a a InputStream from getResourceAsStream(), and I managed to read from the file by passing the returned InputStream to a

相关标签:
2条回答
  • 2020-12-01 18:34

    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.

    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.

    0 讨论(0)
  • 2020-12-01 18:58

    Not directly, no - getResourceAsStream() is intended to return a view on read-only resources.

    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.

    0 讨论(0)
提交回复
热议问题