gpt4 book ai didi

java - 如何使用java在线阅读pdf文件并保存在本地计算机上

转载 作者:行者123 更新时间:2023-12-02 09:04:23 24 4
gpt4 key购买 nike

嗨,我试图在线阅读 PDF 文件,但在本地阅读和编写后。查看文档后,我收到一条错误,内容不受支持。

 URL url1 =
new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf");

byte[] ba1 = new byte[1024];
int baLength;
FileOutputStream fos1 = new FileOutputStream("/mnt/linuxabc/research_paper/Gnostice_PathQuest.pdf");

try {
URLConnection urlConn = url1.openConnection();
/* if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
} else {*/
try {
InputStream is1 = url1.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();


} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
// }

最佳答案

您的 Pdf 链接实际上重定向到 https://www.gnostice.com/downloads.asp ,因此链接后面没有直接包含 pdf 的内容。

尝试使用另一个链接:首先在您选择的浏览器中检查调用 pdf 的 URL 是否会在浏览器中呈现真实的 pdf。

除了 pdf 的 url 和输出路径之外,下面的代码实际上与您的代码相同,而且我还在主方法的签名中添加了异常抛出,并简单地打印了内容类型。

它按预期工作:

public class PdfFileReader {
public static void main(String[] args) throws IOException {

URL pdfUrl = new URL("http://www.crdp-strasbourg.fr/je_lis_libre/livres/Anonyme_LesMilleEtUneNuits1.pdf");
byte[] ba1 = new byte[1024];
int baLength;
try (FileOutputStream fos1 = new FileOutputStream("c:\\mybook.pdf")) {
URLConnection urlConn = pdfUrl.openConnection();
System.out.println("The content type is: " + urlConn.getContentType());

try {
InputStream is1 = pdfUrl.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();


} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
}
}
}

输出:

内容类型为:application/pdf

关于java - 如何使用java在线阅读pdf文件并保存在本地计算机上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com