从本地系统tomcat目录下载pdf文件

时间:2013-06-17 10:20:45

标签: java pdf jsf-2 download

我想在用户点击按钮时下载pdf文件。对于前端我使用的是JSF 2。 其实我想下载pdf文件download image,如primefaces demo

所示

pdf文件存储在我的本地tomcat的Root文件夹中。 我正在以这种方式关注,但它给了我例外

  

java.io.IOException:服务器返回HTTP响应代码:505 for   网址:

URL url;
        URLConnection con;
        DataInputStream dis; 
        FileOutputStream fos; 
        byte[] fileData;  
        try {
            url = new URL("http://localhost:8080/html/pdf/sample.pdf"); //File download Location goes here

            System.out.println("URL "+url.toString());
            con = url.openConnection(); // open the url connection.
            dis = new DataInputStream(con.getInputStream());
            fileData = new byte[con.getContentLength()]; 
            for (int q = 0; q < fileData.length; q++) { 
                fileData[q] = dis.readByte();
            }
            dis.close(); // close the data input stream
            fos = new FileOutputStream(new File("/Users/sample.pdf")); //FILE Save Location goes here
            fos.write(fileData);  // write out the file we want to save.
            fos.close(); // close the output stream writer
        }
        catch(Exception m) {
            System.out.println(m);
        }
  

我提供错误的路径吗?如果是,那么正确的路径是什么   从本地系统tomcat文件夹下载文件如图所示?

1 个答案:

答案 0 :(得分:0)

我忘了把port number 80808052放进去,或者如果你改了就输入你的端口号。

放一个特定的路径。它可以工作

URL url;
URLConnection con;
DataInputStream dis; 
 FileOutputStream fos; 
 byte[] fileData;  
try {
url = new URL("http://localhost:8052/Naveed_workingfiles/a.pdf"); //File download Location goes here

System.out.println("URL "+url.toString());
con = url.openConnection(); // open the url connection.
dis = new DataInputStream(con.getInputStream());
fileData = new byte[con.getContentLength()]; 
for (int q = 0; q < fileData.length; q++) { 
    fileData[q] = dis.readByte();
}
dis.close(); // close the data input stream
fos = new FileOutputStream(new File("C:/Documents and Settings/microsoft/My Documents/Downloads/sample.pdf")); //FILE Save Location goes here
fos.write(fileData);  // write out the file we want to save.
fos.close(); // close the output stream writer
}  catch(Exception m) {
System.out.println(m);
 }