File is not opening in java which is inside jar file - java

I tried to open file form my java application. Using following code from
Open PDF file on fly from Java application
Code:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
When I use path like :
"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf"
it opens. But my file is inside my package
files/test.pdf
and I used
files\\test.pdf
it shows following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.
Why? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants.
Thanks...

getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.

Unfortunately, you cannot load a file through Desktop that is contained in the jar.
However, you are not out of options. A great workaround is to create a temporary file and then open it as detailed here.
Good luck!

Assuming test.pdf is in the package files, try this:
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());

This code is working properly please use this to open pdf file within jar file
try {
// TODO add your handling code here:
String path = jTextField1.getText();
System.out.println(path);
Path tempOutput = null;
String tempFile = "myFile";
tempOutput = Files.createTempFile(tempFile, ".pdf");
tempOutput.toFile().deleteOnExit();
InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
if(Desktop.isDesktopSupported())
{
Desktop dTop = Desktop.getDesktop();
if(dTop.isSupported(Desktop.Action.OPEN))
{
dTop.open(tempOutput.toFile());
}
}
} catch (IOException ex) {}

Related

Java, display chm file loaded from resources in jar

I am trying to display the chm file containing the help which is loaded from resources:
try
{
URL url = this.getClass().getResource("/resources/help.chm");
File file = new File(url.toURI());
Desktop.getDesktop().open(file); //Exception
}
catch (Exception e)
{
e.printStackTrace();
}
When the project is run from NetBeans, the help file is displayed correctly.
Unfortunately, it does not work, when the program is run from the jar file; it leads to an exception.
In my opinion, the internal structure of jar described by URI has not been recognized... Is there any better way? For example, using the BufferReader class?
BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));
An analogous problem with the jpg file has been fixed with the BufferedImage class
BufferedImage img = null;
URL url = this.getClass().getResource("/resources/test.jpg");
if (url!= null)
{
img = ImageIO.read(url);
}
without any conversion to URI...
Thanks for your help...
A .jar file is a zip file with a different extension. An entry in a .jar file is not itself a file, and trying to create a File object from a .jar resource URL will never work. Use getResourceAsStream and copy the stream to a temporary file:
Path chmPath = Files.createTempFile(null, ".chm");
try (InputStream chmResource =
getClass().getResourceAsStream("/resources/help.chm")) {
Files.copy(chmResource, chmPath,
StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(chmPath.toFile());
As an alternative, depending on how simple your help content is, you could just store it as a single HTML file, and pass the resource URL to a non-editable JEditorPane. If you want to have a table of contents, an index, and searching, you might want to consider learning how to use JavaHelp.

java.io.FileNotFoundException: config.properties

I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.

Java - How to open a file located in a jar file

I'm using eclipse. I put a .pdf file in my src folder, i want to open it with the default OS program. The problem is that, if i execute the program with eclipse, i can open it (clicking on a MenuItem) like this :
File memo=new File("src/chap.pdf");
try {
Desktop.getDesktop().open(memo);
} catch (IOException e) {
e.printStackTrace();
}
However, after exporting the project to a jar file, this isn't working anymore. So is there a problem in my code or is there another way to get the file to open when it's in the jar file ?
The src path will not be available after you have exported your program and you should never reference it in any way.
You need to extract the resource from the Jar file and write it to the local disk...
try (InputStream is = getClass().getResourceAsStrea("/chap.pdf")) {
try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(...)) {
// Write contents like you would any file
}
} catch (IOException exp) {
exp.printStackTrace();
}
Then you can use the extracted file with Desktop

HTML file not opening in executable jar

I have a program I have written in Eclipse and it runs fine -- the HTML file opens when I run the program through Eclipse. But when I create a jar file of the program, everything else runs fine except this HTML file won't open in the browser (or anywhere):
operation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File htmlFile = new File("help/operation.html");
Desktop.getDesktop().browse(htmlFile.toURI());
} catch (MalformedURLException MURLe) {
MURLe.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
});
The rest of the program runs fine, and my images and sounds work fine and are opened, but this HTML file will not open in the menu or with the Ctrl+key shortcut. Your help is appreciated. Thanks.
When you have a file inside your jar, you cannot access it like you are doing now.
You need to read it as a stream, that's the only way.
Suppose your project is foo. Then help/operation.html will refer to
..\abc\help\operation.html
But the deployed jar file will not contain it.
You have include this operation.html file in your source code (where you write code).
Then eclipse (or any IDE) will add it into your jar file when you deploy it.
And now you can use your file as follows.
Suppose your file is present in as shown in figure.
Now you can refer your html file from any class. In this example referring it from
Accesser class.
File resFile = new File(Accesser.class.getResource("operation.html").toURI());
If you want to open your file in browser you will have to copy this file into the
user's System.
File htmlFile = new File("operation.html");
if(!htmlFile.exists) {
Files.copy(resFile.toPath(), htmlFile.toPath());
}
Desktop.getDesktop().browse(htmlFile.toURI());
Files is present in java.nio.file package

Read a file from inside of an external Jar file?

I'm trying to read a file from inside an external jar using java..
For example, I have two jar files. One is "foo.jar" the other is "bar.jar". Inside of "bar.jar" is the file "foo-bar.txt". How do i read the file "foo-bar.txt" from inside of "bar.jar" using code in "foo.jar"...? Is this even possible..?
I know that i can read a file from iside of foo.jar using
this.getClass().getClassLoader().getResourceAsStream("foo-bar.txt");
But I don't know how to do it from an external jar.. can someone help me?
Use jar url to open connection the example code
InputStream in = null;
String inputFile = "jar:file:/c:/path/to/my.jar!/myfile.txt";
if (inputFile.startsWith("jar:")){
try {
inputURL = new URL(inputFile);
JarURLConnection conn = (JarURLConnection)inputURL.openConnection();
in = conn.getInputStream();
} catch (MalformedURLException e1) {
System.err.println("Malformed input URL: "+inputURL);
return;
} catch (IOException e1) {
System.err.println("IO error open connection");
return;
}
}
If the jar is in your classpath then getResourceAsStream will work, but note that it will find the first instance in your classpath. If foo.jar and bar.jar both contain this file then it will return whichever jar is first in classpath.
To read it from the jar use JarFile.getEntry and JarFile.getInputStream

Categories

Resources