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

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

Related

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

File is not opening in java which is inside jar file

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) {}

Making folder that will be accessable in jar

I want an option that when ever user selects autologin option...My program will make a folder and it will save a file in it...when the program will start it will look for folder and than file inside it. Problem is when i run my code via netbeans it is running perfectly but when i run it through jar it do not find any folder. Any body can guide me, what is best way to make a folder at run time and access it.
Down is my file writing code...
private void writeSerializableUserObject(boolean isAutoLogin , boolean isAutoRemember){
SerializableUser serializeUserObj = new SerializableUser();
serializeUserObj.setUserEmail(TempSessionUser.getTempUser().getEmail());
serializeUserObj.setUserPassword(TempSessionUser.getTempUser().getPassword());
serializeUserObj.setUserName(TempSessionUser.getTempUser().getF_name());
serializeUserObj.setIsAutoLogin(isAutoLogin);
if(isAutoRemember){
serializeUserObj.setIsAutoRemember(true);
}
System.out.println("in side method.......");
Edit
String path = System.getProperty("user.home");
File file = new File(path+"/user.ser");
if(!file.exists()){
file.mkdir();
}
try {
FileOutputStream fileOutPut = new FileOutputStream(file);
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(fileOutPut);
oos.writeObject(serializeUserObj);
oos.flush();
oos.close();
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Inner catch statment end
} catch (FileNotFoundException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}//Outer Catch statment end
}
After editing it is giving me this exception...within netbeans execution.her uptill HaseebAimal is my home directory path
java.io.FileNotFoundException: C:\Users\HaseebAimal\UserData\user.ser (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
getClass().getResource("/UserData") gives you a location in the class path which sometimes (usually) isn't a directory in the file system. Instead, you should probably pick one or more of:
Prompt the user for a save location.
Use a default location of some file or folder in the user's home directory, which you can get with System.getProperty("user.home").
Save it in the current working directory, which you can get with System.getProperty("user.dir").
The last option is probably the worst unless you know what the working directory will always be because you've handled the installation of your app in some way.
Before creating the FileOutputStream check what do file.canRead() and file.canWrite() return.
You need to make sure that the application can write to the location. If you do not have access to the location, try changing the directory to something else where you have write access.
Something like:
String path = "D:/test";

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

Writing to a file, where is the output file?

FileWriter outFile = null;
try {
outFile = new FileWriter("member.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("test");
Running that command, where is the member.txt ? I am using windows vista. UAC enabled so when I run it, I don't think it's writing to the txt file. txt file is created however, but it's empty.
Relative paths in Java IO are relative to current working directory. In Eclipse, that's usually the project root. You're also writing to out instead of outFile. Here's a minor rewrite:
File file = new File("member.txt");
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write("test");
} catch (IOException e) {
e.printStackTrace(); // I'd rather declare method with throws IOException and omit this catch.
} finally {
if (writer != null) try { writer.close(); } catch (IOException ignore) {}
}
System.out.printf("File is located at %s%n", file.getAbsolutePath());
Closing is mandatory since it flushes the written data into the file and releases the file lock.
Needless to say that it's a poor practice to use relative paths in Java IO. If you can, rather make use of the classpath. ClassLoader#getResource(), getResourceAsStream() and so on.
If the file is successfully created (no exception is raised), it is in the current working directory.
For the Java class you're executing, right click on the file and go to "Run As -> Run Configurations..."
In this screen, go to the "Arguments" tab. At the bottom of the screen, look for the "Working directory" setting. This is the directory that your Java class will run from.
In your example, you're creating "member.txt" in the current directory, so it will show up in whatever location your "Working directory" is set to.
It depends on the IDE you're using also. It will usually go into the same directory that the file.java is located at. I think programs like Eclipse and Netbeans may toss it in a different directory.
If running from Eclipse, the current working directory will be your project's base directory (view your project properties to find that location on disk). You should be able to see the file in the Project Explorer by refreshing the project (click on the project and hit F5).
You can specify an alternative working directory from the Run Configurations dialog under the Arguments tab.

Categories

Resources