0

嗨,我尝试了以下 java 代码,如果我将它们用作 java 应用程序,它们可以正常工作,但是当我在我的 servlet 页面中使用相同的代码时,它们不起作用意味着我无法下载文件。请建议我应该做哪些更改,以便我可以使用 Servlets 下载文件。

一个。

    java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL("http://169.254.174.150:8084/WebApplication1/files/check.txt").openStream());
    File f1 = new File("D:\\a.txt");
    java.io.FileOutputStream fos = new java.io.FileOutputStream(f1);
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
    byte data[] = new byte[1024];
    while (in.read(data, 0, 1024) >= 0) {
        bout.write(data);
    }
    bout.close();
    in.close();
}

湾。http://www.javabeat.net/examples/2012/04/13/download-file-from-http-https-server-using-java/

4

2 回答 2

0

One of the older JavaBeat examples like the one you specified can be found here

I found other solutions too but this seems to be the most comprehensive.

于 2012-04-25T04:51:37.647 回答
0

Couple of things, insetad of writing it to a file try wrting the data directly to the responce. Before writing data you will have to set the following parameters to the responce

        //byte[] filedata = ; intialize your file contents
        String filename = "a.txt";

        //      set the header information in the response.
        res.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";");
        res.setContentType("application/x-unknown");
        ByteArrayInputStream byteStream = new ByteArrayInputStream(filedata);
        BufferedInputStream bufStream = new BufferedInputStream(byteStream);
        ServletOutputStream responseOutputStream = res.getOutputStream();
        int data = bufStream.read();
        while (data != -1)
        {
            responseOutputStream.write(data);
            data = bufStream.read();
        }

        bufStream.close();
        responseOutputStream.close();

where res is a HttpServletResponse object. After this you can write data to responseOutputStream.

于 2012-04-25T04:52:27.557 回答