How to send directly InputStream as response through handler

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

How to send directly InputStream as response through handler

yogesh
Previously, I am using below code to render a html file from handler
            ClassLoader classLoader = this.getClass().getClassLoader();
                File file = new File(classLoader.getResource("raml/api.html").getFile());
                ctx.getResponse().sendFile(file.toPath());
               
But now we are moving to jar from war, so it can't able to find api.html file. After some time spend on internet I come to know that we can't use getResource() to read file within jar file we have to use getResourceAsStream().
So I have written below code to render html file withing jar. Its working fine.

                InputStream is = this.getClass().getResourceAsStream("/raml/api.html");
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            File targetFile = new File("/raml/api1.html");
            new FileOutputStream(targetFile).write(buffer);
            ctx.getResponse().sendFile(targetFile.toPath());
               
Here, the flow is File -> InputStream -> File But I think its not good solution.

Is there any better way in ratpack to send directly InputStream as response through handler?
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: How to send directly InputStream as response through handler

Christoph Dähne
Try sending the bytes of the stream without writing them to the local disk.

                        def read = 1
                        while (read >= 0) {
                            def buffer = new byte[1 * 1024 * 1024]
                            read = stream.read(buffer)
                            if (read > 0) {
                                ctx.response.send(Unpooled.wrappedBuffer(buffer, 0, read))
                            }
                        }
                        stream.close()

Also avoid InputStream.available() to choose your buffer size, since it might be inaccurate.
Loading...