Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpServletResponse PrintWriter to write an InputStream

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

like image 874
user815809 Avatar asked Jan 27 '12 16:01

user815809


People also ask

Is it possible to create a file object from InputStream?

Since Java 7, you can do it in one line even without using any external libraries: Files. copy(inputStream, outputPath, StandardCopyOption. REPLACE_EXISTING);

Can we convert InputStream to file in Java?

Using nio packages exposed by Java 8, you can write an InputStream to a File using Files. copy() utility method.


1 Answers

Resolved using the following

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

OutputStream output = response.getOutputStream();

ByteStreams.copy(inputStream, output);

output.flush();
like image 53
user815809 Avatar answered Sep 27 '22 23:09

user815809