Reputation: 26192
Before, when I used file in my fileWriter it worked, but now, since I'm using getResourceAsStream instead of file, how can I make it work?
FileWriter fstream = new FileWriter(new File("filename"), true);
Now, when I pass
InputStream is = getResourceAsStream("filename");
FileWriter fstream = new FileWriter(is, true);
I had to change it, because when I create a runnable jar with the maven assembly plugin there is no src/main/resources in the jar
EDIT:
thanks to casablanca and others for pointing out my mistakes, follow up :
I need to write to a file, but append to it, with preserving the original content. And I need to know to which file I'm writing of course.
Upvotes: 2
Views: 11309
Reputation: 70691
First of all, to write to a stream, you need a generic stream writer, not a file writer. Secondly, writing means output, so you need an output writer. So the class you're looking for is OutputStreamWriter
.
getResourceAsStream
returns an InputStream
which you can only use for reading, which means you can only use a class such as InputStreamReader
.
Update:
You already have the correct code for appending to a file, using FileWriter
. However, getResourceAsStream
returns a read-only resource, so there is no straightforward method to write data back to it.
Upvotes: 3
Reputation: 10541
InputStream
represents an input stream, so it is not suitable as ouput. You cannot write to an Inputstream
. getResourceAsStream
return a stream for reading a resource, not for writing to it.
I'm affraid there is no easy way to write to resource loaded via the ClassLoader
. One solution would be to read it as Properties
, and then use the store
method to write it to a resource file, obtaining the output stream by other means. You can obtain the URI of the resource file using the classloader, but there is no guarantee you can write to it directly (for example if it is bundled in a signed jar).
Upvotes: 3
Reputation: 3666
if you read the docu, here, you will see, that there is no constructor for your InputStream. Thats why i does not compile. Since you did not ask anything, thats it.
Upvotes: 0