Java是一種流行的編程語言,廣泛用于Web開發(fā)和桌面應用程序的開發(fā)。在許多情況下,我們需要在Java程序中處理PDF文檔,例如下載和查看PDF文件。本文將介紹如何使用Java下載PDF文件和PDF查看器。
1. Java PDF下載
try { String fileURL = "https://example.com/document.pdf"; String saveDir = "/path/to/save/directory"; URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); //檢查是否成功連接到服務器 if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); String contentType = httpConn.getContentType(); int contentLength = httpConn.getContentLength(); //檢查文件名和類型是否可用 if (disposition != null) { //從Content-Disposition中獲取文件名 int index = disposition.indexOf("filename="); if (index >0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { //沒有文件名時從URL中獲取 fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } //輸出日志 System.out.println("Content-Type = " + contentType); System.out.println("Content-Disposition = " + disposition); System.out.println("Content-Length = " + contentLength); System.out.println("filename = " + fileName); //為文件創(chuàng)建輸入流 InputStream inputStream = httpConn.getInputStream(); //為文件創(chuàng)建本地文件輸出流 FileOutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName); //從網(wǎng)絡鏈接讀取數(shù)據(jù)到本地文件 int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("文件已經(jīng)成功下載到:" + saveDir + File.separator + fileName); } else { System.out.println("連接無效,錯誤代碼:" + responseCode); } httpConn.disconnect(); }catch(IOException e){ e.printStackTrace(); }
2. Java PDF查看器
try { String filePath = "/path/to/pdf/file.pdf"; //使用Runtime.exec進行系統(tǒng)調(diào)用打開pdf文件 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + filePath); }catch(IOException e){ e.printStackTrace(); }
總結:
Java下載PDF文件和查看器的代碼相對較易編寫,但需要特別注意的是錯誤處理。下載過程中需要進行網(wǎng)絡請求和文件IO操作,應該使用try-catch語句,防止出現(xiàn)異常。查看器中使用的是Runtime.exec()進行系統(tǒng)調(diào)用,在Windows系統(tǒng)中打開PDF需要使用rundll32命令,而在Mac系統(tǒng)中,則需要使用open命令。