List dirs in a jar
Hi,
i need to scan a directory (resources) for files and if there are any files (there are!) - put all file names in a list. All works fine until I pack all class files and the resources dir in a jar file. I need to run the application packed as a jar file.
Is there any possibility to read a DIRECTORY inside a jar file? I can open files inside the archive, but not directories...
Any help is appreciated :)
Thanks in advance,
Merlin
Perhaps I did not explained my problem very well...
what you propose, JProg, is of course correct, but
what if I don't know the name of the jar file? Can I
determine during the run time the name of the jar file
in which the class files and the resources are
packed?
Now I find a single resource file like that:
this.getClass().getResource("resources/text.properties"
This works fine for files, but not for dirs. If I
request the URL for a dir inside the jar file
this.getClass().getResource("resources/");
I only get a FileNotFoundException: Specified resource
can not be found.
How can I determine the name of the jar in which the
involved class is packed?Hm it's something like this...
Class anyClassOfTheJar;
URL jarURL = anyClassOfTheJar.getProtectionDomain().getCodeSource().getLocation();
Similar Messages
-
Browse files and dirs in the JAR-file
Hi! I'm stuck with a problem concerning browsing a JAR file to find all images, fonts and sound clips. I think this is a pretty straight-forward task, except when I consider that the file I want to browse, is the same file the browser is stored in and running from. I have searched for hours on the internet now, and I still haven't figured out a way to be able to browse my JAR file.
Here is the code I use when I'm not running my project in a JAR-file:
* Load and cache all files (*.ttf, *.png and *.wav) from the resource-directory
public void loadResources() throws FileNotFoundException {
// log available VRAM
log.println("Available VRAM before loading resources: " + graphicsDevice.getAvailableAcceleratedMemory() + " bytes", Log.INIT);
// determine whether or not we are dealing with the contents of a jar-file
jar = getClass().getResource("").getProtocol().startsWith("jar");
// browse all directories
long start, end;
int loadTime = -1;
start = System.nanoTime();
browseDirectory(".." + separator + "resources");
end = System.nanoTime();
loadTime = Math.abs((int)(end - start) / 1000000);
resourcesLoaded = true;
// log
log.println("Resources loaded in " + loadTime + " ms", Log.INIT);
// log available VRAM
log.println("Available VRAM after loading resources: " + graphicsDevice.getAvailableAcceleratedMemory() + " bytes", Log.INIT);
* Browse a directory and load and cache all it's files
* @param path The directory to browse
private void browseDirectory(String path) {
// log
log.println("Browsing directory: " + path.replaceFirst("\\W*", ""), Log.INIT);
try {
if (jar) {
// TODO: enable JAR-browsing by getting the input stream from the JAR-file, then browse through all entries
throw new RuntimeException("Cannot browse JAR-files yet!");
else {
File dir = new File(getClass().getResource(path).toURI());
// browse through the directory
String[] files = dir.list();
File file;
for (String name: files) {
file = new File(dir.getAbsolutePath() + separator + name);
// if this is a new sub-directory, browse it
if (file.isDirectory()) browseDirectory(path + separator + file.getName());
// otherwise, add the file
else addFile(path, name);
catch (Exception e) { e.printStackTrace(); }
} But, as you may see, I need a similar code to browse the JAR-file....please help me!
lhkI worked it out by trying and failing:
* Browse the JAR-file and load all it's relevant files
private void browseJar() {
try {
// convert the resource directory path to a JAR-compatible path
String jarDir = dir.replaceAll("\\" + separator, String.valueOf(jarSeparator));
// get the jar-file and it's entries
Enumeration<JarEntry> entries = new JarFile(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).entries();
// browse the contents of the file
JarEntry entry;
int nameIndex;
String name = null;
String path = null;
while (entries.hasMoreElements()) {
// get the entry
entry = entries.nextElement();
// we only process relevant entries
if (entry.getName().startsWith(jarDir)) {
nameIndex = entry.getName().lastIndexOf(jarSeparator);
name = entry.getName().substring(nameIndex + 1);
// if we find a new directory, we get it's path
if (entry.isDirectory()) {
path = entry.getName().substring(jarDir.length(), nameIndex);
if (path.startsWith(String.valueOf(jarSeparator))) path = path.substring(1) + jarSeparator;
// log (the system-compatible path)
log.println("Browsing directory: " + dir + separator + path.replaceAll(String.valueOf(jarSeparator), "\\" + separator), Log.INIT);
// otherwise, we add the resource
else addFile(path, name);
catch (Exception e) { e.printStackTrace(); }
}As may be seen in the code, I discovered that the regular file separator could not be used in jar paths, which I found strange. I tried a lot to make the regular separator work, but couldn't manage it. Anyway, this code works for me. -
Listing files in a jar, one screen at a time
I need to list all the files in a .jar file from the DOS command line (using jar tf etc.). There are so many files that half of the list scrolls above the top of the window before the end of the list is displayed, so I can't see half the list. How do I tell it to pause the list when the screen is full, then continue scrolling only when I hit come key? I tried using \p (which is used in DOS) but that doesn't work.
Redirect the output to a file, and then use Notepad to display the contents of that file.
jar ... >somefile.txt -
Listing resources in a .jar
How can you list the resources in a jar file, and step through all the different directories.
I want to be able to find out all the images in the /image directory
and load them into memory. The image directory may also include sub directories containing more images.Have you tried JarFile?
There are examples on the web.
http://www.google.co.uk/search?num=20&hl=en&ie=UTF-8&c2coff=1&q=java.util.jar.JarFile+example&btnG=Search&meta= -
How to know the dir where my jar program is stored
I write a swing editor text files.
I make the jar of my program: Editor.jar
Then with jsmooth (open source java wrapper) i make the exe: Editor.exe.
The user can put the exe anywhere in a folder and use it, example:
User have a text file on desktop and want to open it:
User make a double click on file.txt --> Microsoft Windows Xp open my program and load the file.
All work correctly but there is one problem.
My program Editor.exe when is close make a Editor.properties file. I would like this file to be created in the same dir where Editor.exe is stored.
I don't know how to do this thing. I write this code:
public static void save(Properties propertiesFile) { URL jarURL = (PropertiesFile.class.getClassLoader().getResource(".")); FileOutputStream out; System.out.println("dir \n" + jarURL.getFile()); File f = new File(jarURL.getFile()+"Editor.settings"); try { out = new FileOutputStream(f); propertiesFile.store(out, "Program settings"); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); }}
This code is wrong because jarURL.getFile() is the directory where file.txt is stored but i want the dir where Editor.exe is stored.
I try with this line of code:
URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
i get this dir:
/C:/Documents%20and%20Settings/Andrew/Settings%20local/Temp/temp10
.jar
This is a correct dir, because the program is stored ind dir
c:\program files\editor\Editor.exe
Anybody can help me?
THXtry below...
public java.net.URL getResource(String strName)throws java.net.MalformedURLException
String baseURL = getClass().getResource("/resources").getFile(); // ("/resources" ):- is a file /dir stored in in jar
try{
baseURL = java.net.URLDecoder.decode(baseURL,"UTF-8");
}catch(Exception e){}
if(baseURL.startsWith("file:"))
baseURL = baseURL.substring(baseURL.indexOf(":")+1);
java.io.File fBase = new java.io.File(baseURL); // Original URL Ref. To Jar Archive
java.io.File jarFile = fBase.getParentFile(); // Jar File Reference
java.io.File rootDir = jarFile.getParentFile(); // Root Directory which Contains Jar File
java.io.File fileApp = new java.io.File(rootDir,strName); // Requested File/Directory
if(fileApp.exists())
return fileApp.toURL();
else
return null;
}Timir -
Hi ,
Is it possible and how to define additional directories for .jar , htm files in Dev Forms10g...????
For instance , in my forms.conf file.... there are :
# Virtual path mapping for Forms Java jar and class files (codebase)
AliasMatch ^/forms/java/(..*) "C:\oracle\product\DevSuite10g/forms/java/$1"
# Virtual path for JInitiator downloadable executable and download page
AliasMatch ^/forms/jinitiator/(..*) "C:\oracle\product\DevSuite10g/jinit/$1"
# Virtual path for runform.htm (used to run a form for testing purposes)
AliasMatch ^/forms/html/(..*) "C:\oracle\product\DevSuite10g/tools/web/html/$1"
......Thanks a lot
SimonIn this orion-web.xml file... there are entries like...:
<virtual-directory virtual-path="/html"
real-path="C:\oracle\product\DevSuite10g/tools/web/html" />
<virtual-directory virtual-path="/java"
real-path="C:\oracle\product\DevSuite10g/forms/java" />
Where should i put the alternative dir .....(such as the ones i have written in bold below....)
<virtual-directory virtual-path="/html"
real-path="C:\oracle\product\DevSuite10g/tools/web/html" , real-path="C:\oracle\product\DevSuite10g/tools/web/html_2"/>
<virtual-directory virtual-path="/java"
real-path="C:\oracle\product\DevSuite10g/forms/java" , real-path="C:\oracle\product\DevSuite10g/forms/java_2"/>
or
<virtual-directory virtual-path="/html" real-path="C:\oracle\product\DevSuite10g/tools/web/html" />
<virtual-directory virtual-path="/html" real-path="C:\oracle\product\DevSuite10g/tools/web/html_2" />
<virtual-directory virtual-path="/java" real-path="C:\oracle\product\DevSuite10g/forms/java" />
<virtual-directory virtual-path="/java" real-path="C:\oracle\product\DevSuite10g/forms/java_2" />
or where can i find a relative doc.... ????
Many Thanks,
Simon
Message was edited by:
sgalaxy -
List the contents of jar, ear, war files
Hi All,
It has been several years since I have worked in java and now I am trying to get caught back up :-).
My question is: Is there a standard utility that can dump/list the contents of the packaging files: jar, ear, war?
Thanks in advance!You can use winzip. OR you can use the jar command provided in JDK.
jar -tvf <<your archive (jar, war, ear)>> -
UCSM list off all Webinterface .jar files / McAfee blocking ccore.jar
Hi guys,
I am looking for a list of all .jar files UCSM loads on startup, basically the /ucsm/unpacked folder.
We are using MCafee Enterprise AV 8.8 and it seems to block access to the ccore.jar file.
I am trying to get an exclude file rule from our IT for the management servers and I'm wondering if anyone could provide me with a list of those files.
If you know a solution for the issue which doesn't involve exception rules you are welcome to help me
Regards,
ConstantinIf you open ucsm.jnlp file (the file which will be dowloaded to your machine when you try to launch UCSM GUI) in a text editor then you will see entries like,
and that will give you the complete list of jar files downloaded from the switch to your machine for the launching of UCSM GUI.
e.g.
http://java.sun.com/products/autodl/j2se" java-vm-args="-Dsun.java2d.d3d=false -XX:+HeapDumpOnOutOfMemoryError -XX:MaxPermSize=256m" initial-heap-size="128M" max-heap-size="768M"/>
Thanks,
Varun -
How to get a file in the same dir with the jar-executable
Hi,
I need to read/write a file that exists in the same directory with the jar-executable. How can i do that? I think that when i specify no path for the file, the file has to be in current path. (Is that right?)
Note: I do not know in which directory the jar and the file are.
Thanx in advanceHi,
I need to read/write a file that exists in the same
directory with the jar-executable. How can i do that?
I think that when i specify no path for the file, the
file has to be in current path. (Is that right?)
Note: I do not know in which directory the jar and
the file are.
Thanx in advance
When you specify no path for the file, the file has to be in the directory where the virtual machine was started. ( the directory the java command was invoked in .)
If you can't control the directory in which the vm is started, but you know the name of the .jar file you can do the following. This trick takes advantage of the fact that if you are using classes in a jar file, the name of the jar file must be in your classpath.
public static String getPathOfJar( String nameOfJar )
throws Exception
StringTokenizer st = new StringTokenizer(
System.getProperty( "java.class.path" ) ,
System.getProperty( "path.separator" ) );
String jarfile = "";
while ( st.hasMoreTokens() )
String token = st.nextToken();
if ( token.indexOf( nameOfJar ) > -1 )
jarfile = token;
break;
if ( jarfile.equals("") ) throw new Exception( "Jar not found in classpath" );
String path = jarfile.substring( 0 , jarfile.indexOf( nameOfJar ) );
return path;
//To open a file in the same directory as the sun archive tools.jar
File f = new File( getPathofJar( "tools.jar" ) + "someFile.txt" ); -
Hi.
Is there anyway to add jar's to a ejb jar?
(The same way as in a war file. WEB-INF/lib)
And i dont want to unpack the jar files.
i have the same problem with ear files..
Thanks.
/AndersYou have to use an ear file. Package your third party jars inside ear file and
then use "classpath" inside Manifest.mf for ejb.jar file or .war file in order
to reference those jars. This is described here:
http://edocs.bea.com/wls/docs61/ejb/EJB_deployover.html#1074087
For an excellent example on jars depenency in ear downlowd depend.zip from:
http://developer.bea.com/techtracks/ejb/index.jsp
Anders Carlberg <[email protected]> wrote:
Hi.
Is there anyway to add jar's to a ejb jar?
(The same way as in a war file. WEB-INF/lib)
And i dont want to unpack the jar files.
i have the same problem with ear files..
Thanks.
/Anders -
Outputing a dir listing for use as a file sorter
hi all
i was working on using an external *.exe to encode some data and i
need to take a dir listing in so that i can apply the encoding to
certain files, but i am having a little diffuculty in in outputting a
text file from which to scan, i have
i am using labview 6, and the main vi elements i'm using for this
proccess is the list dir vi index array vi and write chars to a file
vi, but i cannot get the file names on a new line for each one, they
are all after each other with one space....
i know in text based programing you can use \n or similar to solve
this, but i am at a loss here with labview
if any one could help i would be most grateful
petermany thanks! i don't know how i could have missed that! :-)
"Greg McKaskle" wrote in message
news:[email protected]..
> > i was working on using an external *.exe to encode some data and i
> > need to take a dir listing in so that i can apply the encoding to
> > certain files, but i am having a little diffuculty in in outputting a
> > text file from which to scan, i have
> > i am using labview 6, and the main vi elements i'm using for this
> > proccess is the list dir vi index array vi and write chars to a file
> > vi, but i cannot get the file names on a new line for each one, they
> > are all after each other with one space....
> > i know in text based programing you can use \n or similar to solve
> > this,
but i am at a loss here with labview
> > if any one could help i would be most grateful
>
>
> The string palette has constants for different linefeed, carriage
> return, or the platform adapting end of line. If you add this
> string character between names, that should get you started.
>
> Greg McKaskle
> -
How can I list all files in a subdirectory in a jar
Hello.
I have wrote a program which lists all class files in given directory.
I used Class.getResource(""), and File.list().
Now I turned the program into single jar file.
It never works.
I know the reason but do not know how to fix the problem.
What can I do?
Thank you in advance.If you are trying to list the files of jar file from java code you can use this code.
Try with the below code
=============================================
try {
// Open the JAR file
JarFile jarfile = new JarFile("filename.jar");
// Get the manifest
Manifest manifest = jarfile.getManifest();
// Get the manifest entries
Map map = manifest.getEntries();
// Enumerate each entry
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
// Get entry name
String entryName = (String)it.next();
// Get all attributes for the entry
Attributes attrs = (Attributes)map.get(entryName);
// Enumerate each attribute
for (Iterator it2=attrs.keySet().iterator(); it2.hasNext(); ) {
// Get attribute name
Attributes.Name attrName = (Attributes.Name)it2.next();
// Get attribute value
String attrValue = attrs.getValue(attrName);
} catch (IOException e) {
=================================================
use import java.util.*;
and import java.io.*; -
How to get .class files from a JAR at runtime
Hi. I wrote a program that load the classes it find in the "prog/components" directory. It enables me to add new components without messing with the code of the main program. Everything worked fine when wrote a batch file - but I want to create a JAR file. In the Batch file I gave the path to those files for the class loader in a loop, and it was "prog.components/" + filename[i] (I get the file names by using a FileFilter).
My question is - how can I obtain the files in the prog/component directory inside the JAR? WHen I left it as it was in the BATCH it didn't work because there wa no prog/component dir outsiede the JAR. What should I do?Thanks man, that was really helpful! I wrote some piece of code that inserts the file names I want to an ArrayList. However, I wonder how you would make the program list all the files in the "prog.jar/prog/components/" directory? I think your code would be better tahn mine since you've coped with it before. Could you write the code snippet?
-
Hi,
I have my jar file created with the main class specified. That works fine but it fails to find associated libraries which I have included in a lib folder in the jar. So my questions is how do I specify on the command line the classpath to look at dirs inside the jar. When I say to look at lib it seems to search for a lib folder in the directory I am running from (as I would expect it to). So how do I tell it from the command line, also is there a way to put this in the Manifest file? Thanks a lot
StephenI don't think this is exactly what I am looking for.
I want something that only downloads the .jar file if
the user chooses an option in a menu. That way
normal users will not have to download unessesary
items. I believe indexing will select appropriate
classes from a jar file the first time the applet is
initialized.
-perciousOn the contrary, I believe it is what you want. This is from the first google hit on "jar indexing":
JAR indexing
If an application or applet is bundled into multiple JAR files, the class loader uses a simple linear search algorithm to search each element of the class path, which may entail the class loader downloading and opening many JAR files until the class or resource is found. If the class loader tries to find a nonexistent resource, all the JAR files within the application or applet will have to be downloaded. For large network applications and applets this could result in slow start up, sluggish response, and wasted network bandwidth.
[Since JDK 1.3, the JAR file format has supported indexing to optimize the process of searching for classes in network applications, especially applets. The JarIndex mechanism collects the contents of all the JAR files defined in an applet or application and stores the information in an index file in the first JAR file. [b]After the first JAR file is downloaded, the applet class loader will use the collected content information for efficient downloading of JAR files. This directory information is stored in a simple text file named INDEX.LIST in the META-INF directory of the root JAR file.
http://www-106.ibm.com/developerworks/library/j-jar/ -
Include jars for compiling and exclude jars for war
Hello,
In the context of using ant to create a war, I have some doubts:
Actually to compile my web application codes, I put in classpath the following two jars as:
<pathelement location="${lib.dir}/${servlet-api.jar}"/>
<pathelement location="${lib.dir}/${jsp-api.jar}"/> without these two jars I would get compiling errors.
To create a war, I have to exclude these two jars:
<lib dir="${webapp.dir}/WEB-INF/lib">
<exclude name="servlet-api.jar"/>
<exclude name="jsp-api.jar"/>
</lib>If I kept these two jars in the war, JBOSS application server would complain of duplicate classes.
My approach works. But my question is:
Is it the best practice to include jars for compiling codes and exclude jars if the application servers already have them?
Best regards,
PengyouYes. That is the best practice.
In fact its the only practice to do it properly.
You are compiling against Interface only. Your code will work as long as that interface is implemented by the server, even if it does different things under the hood. This is what lets your web application work on whatever server you deploy it on - Jboss, Tomcat, Weblogic - it shouldn't matter as they all implement the same basic interfaces.
You could also expand that list to include common APIs which you know are available on your server if you don't want to bundle them with every web application.
JSTL jars are one potential example.
Maybe you are looking for
-
CONTEXT index vs a CTXCAT index
I'm puzzled as to which of these indexes is meant for what purpose. I like the auto-update feature of the CTXCAT index, so I'm leaning that direction. Here's our situation. We have a table with about 2 million rows, where there's an EMPLOYER_NAME fie
-
Itunes wont open - Beging for Help ...
HI i recently buoght an ipod video and i was so happy but then the itunes problems came up at the begining it works but after i restart my comupter i duble click the itunes the hourglass shows for a second or 2 and nothing no error message and no not
-
I just bought a macbook while I was in Canada, so it has a US plug. I'm coming back to the UK in November so will need a UK plug. I've looked in the store and it seems that the best way to get the UK plug is through the world travel kit. Does any one
-
I have uninstalled any cookie management extensions that were supposed to manage cookies. Any ideas?
-
I can't deregister iMessage from my account. I no longer have my iPhone. I have a Samsung 4S and cannot receive text messages with data that come from someone else's iPhone. Apple support wants to charge a one time tech help fee. I don't want to