Listing resources from a resource folder - java

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

Related

is it possible to add a relative path to ClassPathXmlApplicationContext?

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");

Reading files from relative paths on Tomcat

I need to run a web-app on Tomcat, but it cannot read the txt files(from a relative paths as below) on Tomcat. However, it does work if I use a full path.
So I am wondering where can I put these txt files so that when Tomcat started, the app can successfully read the txt files from a relative path.
Currently, the project structure is as follows, the txt files is located on the same directory as src file in Project Explorer in Eclipse.
Project_Name
src
java files
EDGES.txt
NODES.txt
The code is as follows, I am appreciated if someone can give me an answer in details, since I am quite new to Java.
The code is as follows:
public class RouteingDao {
NodeJSONReader nodeInput = new NodeJSONReader("NODES.txt");
EdgeJSONReader edgeInput = new EdgeJSONReader("EDGES.txt");
...
}
The NodeJSONReader/EdgeJSONReader class is as follows:
public class EdgeJSONReader {
private EdgeEntity[] edgeEntity;
// constructor
public EdgeJSONReader(String JSON_FILE) {
edgeEntity = readEntityFromFile(JSON_FILE);
}
// load the JSON data from local file
public EdgeEntity[] readEntityFromFile(String JSON_FILE) {
try {
Reader reader = new FileReader(JSON_FILE);
Gson gson = new Gson();
edgeEntity = gson.fromJson(reader, EdgeEntity[].class);
}
...
}
}
If you are using a servlet, then access the servlet context and the getRealPath method.
this.getServletContext().getRealPath("WEB-INF/nodes.txt")
The relative path sent to getRealPath will be expanded to the location of the files for your web app. You can add any path you like, even to a hidden file in WEB-INF.
From a JSP you can use
${pageContext.servletContext.getRealPath("WEB-INF/nodes.txt")}
Be careful, this will be in the build directory, so any changes to nodes.txt will not be saved to the original file.

load a folder from a jar

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.

How can I get real path for file in my WebContent folder?

I need to get real path for file in my WebContent directory, so that framework that I use can access that file. It only takes String file as attribute, so I need to get the real path to this file in WebContent directory.
I use Spring Framework, so solution should be possible to make in Spring.
If you need this in a servlet then use getServletContext().getRealPath("/filepathInContext")!
getServletContext().getRealPath("") - This way will not work if content is being made available from a .war archive. getServletContext() will be null.
In this case we can use another way to get real path. This is example of getting a path to a properties file C:/Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties:
// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");
// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");
if (decoded.startsWith("/")) {
// path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");
you must tell java to change the path from your pc into your java project so
if you use spring use :
#Autowired
ServletContext c;
String UPLOAD_FOLDEdR=c.getRealPath("/images");
but if you use servlets just use
String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");
so the path will be /webapp/images/ :)
In situations like these I tend to extract the content I need as a resource (MyClass.getClass().getResourceAsStream()), write it as a file to a temporary location and use this file for the other call.
This way I don't have to bother with content that is only contained in jars or is located somewhere depending on the web container I'm currently using.
Include the request as a parameter. Spring will then pass the request object when it calls the mapped method
#RequestMapping .....
public String myMethod(HttpServletRequest request) {
String realPath = request.getRealPath("/somefile.txt");
...
You could use the Spring Resource interface (and especially the ServletContextResource): http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/io/Resource.html
This approach uses the resource loader to get the absolute path to a file in your app, and then goes up a few folders to the app's root folder. No servlet context required! This should work if you have a "web.xml" in your WEB-INF folder. Note that you may want to consider using this solely for development, as this type of configuration is usually best stored externally from the app.
public String getAppPath()
{
java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
String filePath = r.getFile();
String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();
if (! filePath.contains("WEB-INF"))
{
// Assume we need to add the "WebContent" folder if using Jetty.
result = FilenameUtils.concat(result, "WebContent");
}
return result;
}
my solve for: ..../webapps/mydir/ (..../webapps/ROOT/../mydir/)
String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
Files.createDirectories(Paths.get(dir));
try to use this when you want to use arff.txt in your development and production level too
String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");

How can I get relative path of the folders in my android project?

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

Categories

Resources