Search code examples
javaoutputstream

write multiple images to outputstream in java


I have a folder called images under resources folder in eclipse. And I have multiple images in images folder. I want to display all the images in my browser by calling a web-service. I have tried the following code.I am able to retrieve only one image.I want this for multiple images.How can I do this?

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("images/").getPath());

            final String[] EXTENSIONS = new String[]{
                    "png","jpg"// and other formats you need
            };
            // filter to identify images based on their extensions
            final FilenameFilter IMAGE_FILTER = new FilenameFilter() 
            {

                @Override
                public boolean accept(final File dir, final String name) {
                    for (final String ext : EXTENSIONS) {
                        if (name.endsWith("." + ext)) {
                            return (true);
                        }
                    }
                    return (false);
                }
            };
            if (file.isDirectory()) 
            {   
                 //list of files I get
                for (final File fi : file.listFiles(IMAGE_FILTER)) 
                {
                    OutputStream out =null;
                    OutputStream out1 =null;
                    BufferedImage bi =null;
                    try 
                    {
                        System.out.println("file" +fi);
                        //I get different files from images folder and add that to bufferedImage.
                        bi= ImageIO.read(fi);

                        response.setContentType("image/jpeg");
                        out= response.getOutputStream();
                        ImageIO.write(bi, "png", out);
                        ImageIO.write(bi, "jpg", out);
                        out.close();
                    }
                    catch (final IOException e) 
                    {
                        // handle errors here
                        e.printStackTrace();
                    }
                }
            }

Solution

  • Resources are not files. There is no guarantee that they will even exist in a filesystem, only inside a JAR or WAR file. So using File methods isn't going to work.

    In any case just serializing a stream of images to a browser isn't going to work either. You should be generating an HTML page with <img> elements in it, with URLs for the images, and organizing that those URLs are downloadable. Probably using the resource mechanism isn't appropriate in the first place.