I am having a web application having following structure:
WEB-INF
|-classes
|-templates
|-abc.properties
|- xyz.properties
|-lib
|-internal.jar (all classes of our application)
|- other jars
These are bundled as a war
I want to get name of the files present in WEB-INF/classes/templates
Also I want to get the file object of a file in WEB-INF/classes/templates based on name of the file.
NOTE: Above operation needs to be done from one of the class present in internal.jar. Basically they are on classpath
I want to get the file object of a file in WEB-INF/classes/templates based on name of the file
With java.io.File, you can't do that.
With the java.nio.file API, you can:
final Path warpath = Paths.get("path to your war file here");
final URI uri = URI.create("jar:" + warpath.toUri());
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap());
) {
final Path templates = zipfs.getPath("/WEB-INF/classes/templates");
// walk "templates" with Files.walkFileTree()
}
Related
I have a file in java under the src folder, I want to get its path at runtime relative to the source folder.
For example-
myProject
-- src
-- packageOne
-- SomeFile.java
I would like to have the result packageOne/SomeFile.java. I couldn't find a way, I tried getPath(), getAbsoultePath() and every similar method.
You want to construct a relative path. AFAIK there is no ready function to use.
Given that you have one of the ancestor nodes (src) and you have SomeFile.java, the following code might work but I did not try...
File src = new File("...");
File somefile = new File("...");
String relpath = somefile.getName();
File cursor = somefile.getParentFile();
while (!cursor.getAbsolutePath().equals(src.getAbsolutePath()) {
somefile = cursor.getName() + File.pathSeparator + somefile;
}
System.out.println("relative path: "+relpath);
I want to use ClassPathXmlApplicationContext to load the context from xml configuration files. The files are stored in a subfolder of a "ConfigFilesFolder".
1) "ConfigFilesFolder" is already a part of classpath and I can load any xml file present in that folder.
ex: context = new ClassPathXmlApplicationContext("someconfiguration.xml");
in the above I am passing the name of file as a string and works well.
My Requirement is :
ConfigFilesFolder/somesubfolder
newcontext = new ClassPathXmlApplicationContext("someconfiguration.xml");
I want to load the files from subfolder (somesubFolder) of "ConfigFilesFolder" using ClassPathXmlApplicationContext("nameofFile.xml").
where someconfiguration.xml is a part of somesubFolder.
PS: I cannot use the FileSystemXmlApplicationContext bcz of some restriction.
You can indeed use folders in classpath - the entries in the classpath are the "root", and any folder in them can be relatively accessed, so in your case:
newcontext = new ClassPathXmlApplicationContext("/somesubfolder/someconfiguration.xml");
All our jars contain a certain file version.properties which contains specific information from the build.
When we start a jar from command line (with several jars on the class path), we would like access the version.properties from the same jar. To be more precise: We would like to write Java code that gives us the content of the properties file in the jar where the calling class file resides.
The problem is that all jars on the class path contain version.properties and we do not want to read the first on the class path but the one from the correct jar. How can we achieve that?
Funny problem. You have to find the location of a representative class of the particular jar and use the result to build the URL for the properties file. I hacked together an example using String.class as example and access MANIFEST.MF in META-INF, since the rt.jar has no properties in it (at least a quick jar tf rt.jar | grep properties resulted in zero results)
Class clazz = String.class;
String name = clazz.getName().replace('.', '/') + ".class";
System.out.println(name);
String loc = clazz.getClassLoader().getResource(name).toString();
System.out.println(loc);
if (loc.startsWith("jar:file")) {
String propertyResource = loc.substring(0, loc.indexOf('!')) + "!" + "/META-INF/MANIFEST.MF";
InputStream is = new URL(propertyResource).openStream();
System.out.println(propertyResource);
Properties props = new Properties();
props.load(is);
System.out.println(props.get("Implementation-Title"));
}
Let's say I have a package: com.example.resources and inside it I have picture.jpg and text.txt - How can I use only the package path to identify the absolute filepath of picture.jpg and text.txt?
Is this correct?
File file1 = new File("/com/example/resources/picture.jpg");
file1.getAbsolutePath();
File file2 = new File("/com/example/resources/text.txt");
file2.getAbsolutePath();
"I'm trying to reference those files within the application so that when I deploy the application to different systems I won't have to reconfigure the location of each resource "
You don't want to use a File, which will load from the file system of the local machine, you want to load through the class path, as that's how embedded resources should be read. Use getClass().getResourceAsStream(..) for the text file and getClass().getReource(..) for the image
Your current path you're referencing looks like it should work, given the package name you've provided.
Take a look at this answer and this answer as some references.
I've figured out how to do it. Here is the code that I used:
public String packagePathToAbsolutePath(String packageName, String filename) {
String absolutePath = "File not found";
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
File[] files = new File(root.getFile()).listFiles();
for (File file : files) {
if (file.getName().equals(filename)) {
absolutePath = file.getName();
return absolutePath;
}
}
return absolutePath;
}
This method was really useful because it allowed me to configure the resource paths within the application so that when I ran the application on different systems I didn't have to reconfigure any paths.
I am trying to access a directory inside my jar file. I want to go through every of the files inside the directory itself. I tried using the following:
File[] files = new File("ressources").listFiles();
for (File file : files) {
XMLParser parser = new XMLParser(file.getAbsolutePath());
// some work
}
If I test this, it works well. But once I put the contents into the jar, it doesn't because of several reasons. If I use this code, the URL always points outside the jar.
structure of my project :
src
controllers
models
class that containt traitement
views
ressources
See this:
How do I list the files inside a JAR file?
Basically, you just use a ZipInputStream to find a list of files (a .jar is the same as a .zip)
Once you know the names of the files, you can use getClass().getResource(String path) to get the URL to the file.
I presume this jar is on your classpath.
You can list all the files in a directory using the ClassLoader.
First you can get a list of the file names then you can get URLs from the ClassLoader for individual files:
public static void main(String[] args) throws Exception {
final String base = "/path/to/folder/inside/jar";
final List<URL> urls = new LinkedList<>();
try (final Scanner s = new Scanner(MyClass.class.getResourceAsStream(base))) {
while (s.hasNext()) {
urls.add(MyClass.class.getResource(base + "/" + s.nextLine()));
}
}
System.out.println(urls);
}
You can do whatever you want with the URL - either read and InputStream into memory or copy the InputStream into a File on your hard disc.
Note that this definitely works with the URLClassLoader which is the default, if you are using an applet or a custom ClassLoader then this approach may not work.
NB:
You have a typo - its resources not ressources.
You should use reverse domain name notation for your project, this is the convention.