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");
Related
I created a data folder beside the js folder in resource/static at the backend of my spring boot application.
I want to list its content in a selection for the user.
I was able to list it if I use the File and Path functions of the base Java. But I don't like this solution, because the path could change in different environment of our system.
I can load a file with org.springframework.core.io.ResourceLoader. I like this solution better as it is independent of the file path of my system. But I did not found the way to list the files in a given resource folder.
Do you have any idea?
Finally I moved my data folder to the WEB-INF.
And I can list the content of it with the following code:
#Autowired
ServletContext context;
public Collection<String> getFileList(String path) {
Collection<String> result = new ArrayList<String>();
Set<String> paths = context.getResourcePaths(path);
for (String p : paths) {
String[] parts = p.split("/");
result.add(parts[parts.length-1]);
}
return result;
}
And I call it with the following parameter:
getFileList("/WEB-INF/data");
This solution works if the WEB-INF folder is unpacked during deploy. And also works when the data folder remains in the war archive.
Check this out :)
You can also read about Java Reflection
Right now I'm manually writing song file names into a String array, then sending the strings to InputStream is = this.getClass().getResourceAsStream(filename); to play the song.
I would rather loop through all the song names in my resources folder and load them into the array so that each time I add a song, I don't need to manually type it into the array.
All of my songs are located in resources folder:
Is there a java method or something to grab these names?
The files need to work when I export as .jar.
I thought I could use something like this?
InputStream is = this.getClass().getClassLoader().getResourceAsStream("resources/");
Is there a listFiles() or something for that?
Thanks
No, because the classpath is dynamic in Java. Any additional Jar could contribute to a package, a classloader can be as dynamic as imaginable and could even dynamically create classes or resources on demand.
If you have a specific JAR file and you know the path within that JAR file then you could simply treat that file as archive and access it via java.util.jar.JarFile which lets you list all entries in the file.
JarFile jar = new JarFile("res.jar");
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
System.out.println(entry.getName());
}
If you want to do this without knowing the JAR filename and path (e.g. by a class within the JAR itself) you need to get the filename dynamically as Evgeniy suggested; just use your own class name (including package; your screenshot looks like you are in default package, which is a bad idea).
You can try something like this
Enumeration<URL> e = ClassLoader.getSystemResources("org/apache/log4j");
while (e.hasMoreElements()) {
URL u = e.nextElement();
String file = u.getFile();
...
file:/D:/.repository/log4j/log4j/1.2.14/log4j-1.2.14.jar!/org/apache/log4j
extract jar path from here and use JarFile class to know org/apache/log4j contents.
If it is unpacked, you will get straight path and use File.listFIles
In my app, I used this code:
File DirectoryPath = cw.getDir("custom", Context.MODE_PRIVATE);
While creating a directory, and it returns:
/data/data/com.custom/app_custom**
So my question is why this app_ appears along with directory name. I know its default, but what actually it means?
And secondly, how can I create a sub-directory inside my directory i.e. app_custom in this case. if anyone knows please help me to understand this concept of getDir.
As far as I think, automatic "app_" added to user created data folders avoid any conflicts with system predefined application folders (folders inside application data folder i.e. cache, contents, databases etc. which are automatically created).
One method to create a sub folder inside those "app_..." folders, get absolute path of "app_..." folder, append required folder name to that and create using mkdirs()
e.g.
File dir = new File(newFolderPath);
dir.mkdirs()
Note: sub folders do not get "app_..." prefix
You can create a new Directory using the path that you are getting from getDir(),
File file = getDir("custom", MODE_PRIVATE);
String path = file.getAbsolutePath();
File create_dir = new File(path+"/dir_name");
if(!create_dir.exists()){
create_dir.mkdir();
}
How can I get the relative path of the folders in my project using code?
I've created a new folder in my project and I want its relative path so no matter where the app is, the path will be correct.
I'm trying to do it in my class which extends android.app.Activity.
Perhaps something similar to "get file path from asset".
Make use of the classpath.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("path/to/folder");
File file = new File(url.toURI());
// ...
Are you looking for the root folder of the application? Then I would use
String path = getClass().getClassLoader().getResource(".").getPath();
to actually "find out where I am".
File relativeFile = new File(getClass().getResource("/icons/forIcon.png").toURI());
myJFrame.setIconImage(tk.getImage(relativeFile.getAbsolutePath()));
With this I found my project path:
new File("").getAbsolutePath();
this return "c:\Projects\SampleProject"
You can check this sample code to understand how you can access the relative path using the java sample code
import java.io.File;
public class MainClass {
public static void main(String[] args) {
File relative = new File("html/javafaq/index.html");
System.out.println("relative: ");
System.out.println(relative.getName());
System.out.println(relative.getPath());
}
}
Here getPath will display the relative path of the file.
In Android, application-level meta data is accessed through the Context reference, which an activity is a descendant of.
For example, you can get the source directory via the getApplicationInfo().sourceDir property.
There are methods for other folders as well (assets directory, data dir, database dir, etc.).
Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images.
I found in search that in JAVA, we can get path from Root to folder which we specify as,
String myStorageFolder= "/images"; // this is folder name in where I want to store files.
String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);
Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,
C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images
With System.getProperty("user.dir") you get the "Base of non-absolute paths" look at
Java Library Description
So I'm trying to add some ability to my project to allow user-defined properties in my deployment artifact - a simple key:value .properties file. I place the service.properties file in
war/WEB-INF/my-service.properties
And in my ServiceImpl.java constructor I have the following:
String propertiesFileName = "my-service.properties";
URL propertyURL = ClassLoader.getSystemResource(propertiesFileName);
URL propertyURL2 = this.getClass().getClassLoader().getResource(propertiesFileName);
URL propertyURL3 = this.getClass().getClassLoader().getResource( "WEB-INF/" + propertiesFileName);
URL propertyURL6 = this.getClass().getClassLoader().getResource(
"E:/Projects/eclipse-workspace/projectName/war/WEB-INF/" + propertiesFileName);
All instances of Property URL are null. I know I'm missing something absolutely obvious, but I need a second pair of eyes. Regards.
EDIT:
Ah, it seems I was confused as the default GAE project creates a logging.properties file in /war. From the Google App Engine documentation:
The App Engine Java SDK includes a template logging.properties file, in the appengine-java-sdk/config/user/ directory. To use it, copy the file to your WEB-INF/classes directory (or elsewhere in the WAR), then the system property java.util.logging.config.file to "WEB-INF/classes/logging.properties" (or whichever path you choose, relative to the application root). You can set system properties in the appengine-web.xml file, as follows:
Try putting the service.properties in WEB-INF/classes. Then it should be accessible just with :
this.getClass().getClassLoader().getResourceAsStream("/filename.properties");
As Mike mentioned in his comment to jsights answer, it worked for me if I used
this.getClass().getClassLoader().getResourceAsStream("filename.properties");
(removed the first slash) after placing the file in WEB-INF/classes.
I think what you will need is something like this:
String filePath = servletContext.getRealPath("/WEB-INF/views/") + "/" + mav.getViewName() + ".vm";
FileInputStream in = new FileInputStream(filePath);
I get the servletContext from spring: #Autowire ServletContext.