[英]Java: inputStream = null from a pdf File in resources
我嘗試打開一個pdf文件,並將其顯示在客戶端的桌面上。 我在Tomcat服務器上使用Java。 該文件位於項目的資源文件夾中,而構建后位於WEB-INF / resources / in.pdf中
inputStream返回null,如何找到文件的真實路徑?
這是代碼:
try{
if (Desktop.isDesktopSupported()) {
File file = new File("out.pdf");
if (!file.exists()) {
InputStream inputStream = ClassLoader.getSystemClassLoader()
.getResourceAsStream("/WEB-INF/resources/in.pdf");
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}
Desktop.getDesktop().open(file);
}
}catch(Exception e1)
{
e1.printStackTrace();
}
現在,getResourceAsStream引用資源,類路徑上的文件,可能包裝在jar或war中。
然后,WEB-INF再次是Web服務器目錄,並且路徑不是WEB-INF / classes或其他內容。 因此,您必須位於servlet中,並檢索Web目錄/ WEB-INF的文件系統路徑。
File file = new File("out.pdf");
if (!file.exists()) {
File source = request.getServletContext()
.getRealPath("/WEB-INF/resources/in.pdf");
Files.copy(source.toPath(), file.toPath());
}
然后,當前桌面再次應顯示PDF(Web服務器和桌面在同一台計算機上)。
如果服務器是一台遠程計算機,則除某些元信息文件外,一般來說WEB-INF應該不可訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.