Read a file from inside of an external Jar file? - java

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

Related

FileNotFoundException while getting file from resources folder using getResource()

I need to get this file from the resources folder in the File object, not in InputSream.
I am using below code, working file on eclipse but FoleNotFoundException on the server. )Using AWS EC2)
Code:
URL res = ResidentHelperService.class.getClassLoader().getResource("key.pem");
System.out.println("resource path2 :" + res);
File privateKeyFile = Paths.get(res.toURI()).toFile();
After printing path looks like:
:jar:file:/home/centos/myproject/microservices/user-service/target/user-service-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/project-common-utility-0.0.1-SNAPSHOT.jar!/key.pem
I have added dependency on the common jar to user service pom.
Please help me to get the file from resources of a common project.
If you have your file in resources folder, the easiest way to access it from the code is probably to use org.springframework.util.ResourceUtils class that Spring provides:
try {
final File file = ResourceUtils.getFile("classpath:key.pem");
....
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Perhaps this way can help you with your issue.

FileInputStream not working in web application

We are trying to read a property file in a servlet using fileInputStream.
However we are constanlty getting a file not found exception.
This is the piece of code we are using
Properties properties = new Properties();
File propertyFile = new File("config" + File.separatorChar + "abc.properties");
try {
FileInputStream propertyFileStream = new FileInputStream(propertyFile);
properties.load(propertyFileStream);
propertyFileStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
While using getResourceAsStream it is working fine.
However we need to understand why FileInputStream is not working.
We have placed the config\abc.properties file in the webInf. We have also tried placing it in the src folder(java classpath), the webContent folder, the WebInf\Classes folder but no success.
Resources are not files. They don't live in the file system and they cannot be accessed via File or FileInputStream.
You should be using Class.getResource().
Try by using
ResourceBundle resource = ResourceBundle.getBundle("test");
String VALUE1=resource.getString("KEY1");
String VALUE2=resource.getString("KEY2");
You should use this code to get resources on web application, because the path must be taken from ServletContext, I think that's what you're looking for, if you are inside Servlet:
InputStream is = getContext().getResourceAsStream("/WEB-INF/yourFolder/abc.properties");
to get the full path for your interest:
String fullPath = getContext().getRealPath("/WEB-INF/yourFolder/abc.properties");

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

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

Categories

Resources