1

So this is the code I have, which already works:

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws Exception {
        String pathToFile = "myimage.jpg";
        File file = new File(pathToFile);
        response.setHeader("Content-Type", "image/jpeg");
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
        Files.copy(file.toPath(), response.getOutputStream());
        response.flushBuffer();
    }
}

However, I must make this work with JDK 1.6.

Files.copy is only available with Java 1.7.

Any suggestions?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319

2 Answers2

2

You can use Apache commons IOutils.

IOUtils.copy(InputStream input, OutputStream output)
Jeet
  • 248
  • 1
  • 8
1

Java 6 didn’t comes with any ready make file copy function, you have to manual create the file copy process. To copy file, just convert the file into a bytes stream with FileInputStream and write the bytes into another file with FileOutputStream.

As there's no way to do this a lot easier with JDK methods.You could use IOUtils from Apache Commons IO, it also has a lot of other useful things.

IOUtils.copy(inputStream, outputStream);

Or else using Guava's ByteStreams.copy() you can achieve the same functionality.

ByteStreams.copy(inputStream, outputStream);
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
Ramesh Papaganti
  • 7,311
  • 3
  • 31
  • 36