How to run a PDF file in Java?

I created a Java application in Netbeans and I want to run a PDF file at the click of a button.

First, I placed the file “manual.pdf” in the directory where I have my classes, and I tried this code:

if(Desktop.isDesktopSupported()) { try { File file= new File("manual.pdf"); Desktop.getDesktop().open(file); } catch(IOException ex) {...} 

but when I ran it, he said that the file does not exist, so I put

 System.out.println(file.getAbsolutePath()); 

to see the path to the file that he was trying to open, and that was

 C:\Users\adrian\Documents\Mis Programas\Convertron\manual.pdf 

but the file was in

 C:\Users\adrian\Documents\Mis Programas\Convertron\src\org\sicadcam\convertron\manual.pdf 

He looked for a file in the project root directory.

When I put the manual.pdf file in the root directory, it worked, but when I ran the executable jar in the dist directory, it didn’t.

Then i tried with

 File file = new File(ConvertronController.class.getResource("manual.pdf").toExternalForm()); 

just to see what happens, but it didn’t work.

How can I make it look for a file in the same directory where the class is?

Or where should I put the file so that when I create the application it works?

+4
source share
2 answers

You can put a PDF document in a Java package, for example. resources , as well as the following project structure:

 TestProject | \---src | +---org | \---paulvargas | \---test | OpenTest.java | \---resources manual.pdf 

To open a file:

 package org.paulvargas.test; import java.awt.Desktop; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; public class OpenTest { public static void main(String[] args) throws Exception { if (Desktop.isDesktopSupported()) { // File in user working directory, System.getProperty("user.dir"); File file = new File("manual.pdf"); if (!file.exists()) { // In JAR InputStream inputStream = ClassLoader.getSystemClassLoader() .getResourceAsStream("resources/manual.pdf"); // Copy file 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(); } // Open file Desktop.getDesktop().open(file); } } } 
+5
source

I used this past:

getClass().getResource("a_file.txt");

In this case, the class from which it is called is in the same directory as a_file.txt .

0
source

Source: https://habr.com/ru/post/1484300/


All Articles