Question

I have a HttpServletResponse object and need to write a file contained in the jar. The following code segments do not work for me.

URI uri = <myclass>.class.getResource("/" + filename).toURI(); 
PrintWriter out = response.getWriter();
File f = new File(uri); 
FileReader bis = new FileReader(f);
char[] buff = new char[1024];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    out.write(buff, 0, bytesRead);
}

I know that this will work

InputStream inputStream = <myclass>.class.getResourceAsStream("/" + filename);

but I cannot get the PrintWriter out.write to write the inputStream.

Can anyone tell me how this can be done.

Thanks

Was it helpful?

Solution

Resolved using the following

InputStream inputStream = KCSSchemaController.class.getResourceAsStream("/" + schemaname);

OutputStream output = response.getOutputStream();

ByteStreams.copy(inputStream, output);

output.flush();

OTHER TIPS

need to write a file contained in the jar.

That's not possible this way. You'd basically need to get an absolute disk file system path to the JAR file, extract it using JarInputStream (a JAR is basically a ZIP file which follows a specific folder structure and get special treatment by Java), edit/add the file in the extracted folder structure and then package it again using JarOutputStream. You'll possibly need to reload it afterwards using a (custom) ClassLoader if you need the changed JAR contents later during runtime.

This is however pretty complicated and makes no sense. As a completely different alternative, do not attempt to change the JAR, but just store the data somewhere else, e.g. on a fixed location on disk file system, or in a database, or as an user/system preference, etcetera. Which way to choose depends on the concrete functional requirement which is not clear from the question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top