简体   繁体   English

打开打包在 JAR 中的 PDF 文件

[英]Opening a PDF file that is packaged in a JAR

I am trying to open a PDF file that is packaged into the jar file during runtime.我正在尝试打开一个在运行时打包到 jar 文件中的 PDF 文件。 The basic idea is that the user clicks the help option and then it displays a help file that is a PDF.基本思想是用户单击帮助选项,然后它会显示一个 PDF 格式的帮助文件。 Right now I have this in LineFit.class in the linefit package to try and open the help PDF:现在我在 linefit 包中的 LineFit.class 中有这个来尝试打开帮助 PDF:

try {
  File test = new File(LineFit.class.getClass().getResource("/linefit/helpTest.pdf").toURI());
  try {
      Desktop.getDesktop().open(test);
  } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
  } 
} catch (URISyntaxException e2) {
  // TODO Auto-generated catch block
  e2.printStackTrace();
}

It works in eclipse when I run it but if I try to export it to a runnable JAR file it does not open the PDF file and when I look into the JAR, the PDF is in the same folder as when it was in eclipse.当我运行它时它在 eclipse 中工作,但如果我尝试将它导出到一个可运行的 JAR 文件,它不会打开 PDF 文件,当我查看 JAR 时,PDF 与它在 eclipse 中时位于同一文件夹中。

new File(URI) only works for file: URIs. new File(URI)仅适用于file: URI。 When a classloader finds a resource in a jar, it returns a jar URI, for example jar:file:/C:/Program%20Files/test.jar!/foo/bar .当类加载器在 jar 中找到资源时,它会返回一个jar URI,例如jar:file:/C:/Program%20Files/test.jar!/foo/bar

Fundamentally, the File class is for files on the filesystem.从根本上说, File类用于文件系统上的文件。 You can't use it to represent a file within a JAR or another archive.您不能使用它来表示 JAR 或其他存档中的文件。 You're going to have to copy the file out of the jar and into a regular file, then create a File referencing this new file.你将不得不将文件复制出来的罐子,并成为一个普通的文件,然后创建一个File引用这个新文件。 To read the file from the jar, you could use JarURLConnection.getInputStream with the URL you have, or you could call ClassLoader.getResourceAsStream .要从 jar 中读取文件,您可以将JarURLConnection.getInputStream与您拥有的 URL 一起使用,或者您可以调用ClassLoader.getResourceAsStream

Try this:尝试这个:

Make sure the path of pdf file is relative path when you use MethodHandles.lookup().lookupClass().getClassLoader()使用MethodHandles.lookup().lookupClass().getClassLoader()时确保pdf文件的路径是相对路径

InputStream is = MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream("doc/example.pdf");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
            System.out.println(thisLine);
         } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM