Get all file names from resource folder in java project - java

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

Related

Searching Through a Directory

Hello one of the parts of a program i'm working on requires the ability to search through a directory. I understand how using a path variable works and how to get to a directory; but once you are in the directory how can you distinguish files from one another? Can we make an array/or a linked list of the files contained within the directory and search using that?
In this specific program the goal is for the user to input a directory, from there go into sub-directory and find a file that ends with .mp3 and copy that to a new user created directory. It is certain that there will only be one .mp3 file in the folder.
Any help would be very much appreciated.
Seeing what you say, I will suppose that you use the java7 Path api.
To know if a path is a directory or a simple file, use Files.isDirectory(Path)
To list the files / directories in your directory, use Files.list(Path)
The javadoc of the Files class : http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html
If you use the "old" java.io.File api, then you have a listFiles method, which can take a FileFilter as argument to filter, for exemple, only the files ending with ".mp3".
Good luck
Get Files as so:
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
for (File file : files)
if (file.isFile())
results.add(file.getName());
If you want the extension:
public static String getExtension(String filename){
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0)
extension = fileName.substring(i+1);
return extension;
}
There are other ways to get file extensions listed here but they usually require a common external library.
You can use the File object to represent your directory, and then use the listFiles() (which return an array of files File[]) to retrieve the files into that directory.
If you need to search through subdirectories, you can use listFiles() recursively for each directory you encounter.
As for the file extension, the Apache Commons IO library has a neat FileFilter for that: the SuffixFileFilter.

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.

Make all images in a folder into IconImages

I'm trying to figure out how to add a lot of images into my Java program without having to add every file name in the code.
So I want to take all the .png images in the correct folder and make them into an IconImage and then place them in an ArrayList.
What I've got right now is this.
private void fillList()
{
File[] files = new File("C:/Users/marre/Google Drive/Java/lek/imageplay/src/img").listFiles();
for (File f : files)
{
if (f.isFile())
{
ImageIcon tempIcon = new ImageIcon(getClass().getResource("/img/"+f.getName()));
List.add(tempIcon);
}
}
}
This works the way I want it to regarding getting the names of all images. But the file only reads from absolute file path.
What can I use instead to get the same result, but that works within .jar file (so it reads from src/img/ and not the whole c:/ bla bla..)?
I'm not sure if this will be helpful but I had a similar issue in attempting to obtain files within a jar file. In the case this can be useful to you, my approach was to obtain the URL for the files inside the jar using the ClassLoader:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("src/img/");
Check inside your jar to make sure of the directory structure for the images so you can specify the correct relative path.
Keep in mind, a jar is a packaged form, so this will most likely return a zipped file (and not a simple File object). You might have to dabble in ZipFile.
ZipFile folderInsideJar = new ZipFile(new File(url.getPath());
Enumeration<? extends ZipEntry> entries = folderInsideJar.entries();
while (entries.hasMoreElements()) {
// ideally this would be your image file, zipped
ZipEntry childFile = entries.nextElement();
// ... etc ...
}
For environments such as JBoss, etc, you might also get virtual files (vfsfile/vfszip). Point being, you can determine what you are dealing with by looking at the result URL.getProtocol().
It would also appear ImageIcon has a constructor that takes a URL. You might try giving this a shot to see if it handles the "resource inside jar" case before manually attempting to retrieve the zip file.

Why app_ appears while creating directory using ContextWraper.getDir

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 to walk through Java class resources?

I know we can do something like this:
Class.class.getResourceAsStream("/com/youcompany/yourapp/module/someresource.conf")
to read the files that are packaged within our jar file.
I have googled it a lot and I am surely not using the proper terms; what I want to do is to list the available resources, something like this:
Class.class.listResources("/com/yourcompany/yourapp")
That should return a list of resources that are inside the package com.yourcompany.yourapp.*
Is that possible? Any ideas on how to do it in case it can't be done as easily as I showed?
Note: I know it is possible to know where your jar is and then open it and inspect its contents to achieve it. But, I can't do it in the environment I am working in now.
For resources in a JAR file, something like this works:
URL url = MyClass.class.getResource("MyClass.class");
String scheme = url.getProtocol();
if (!"jar".equals(scheme))
throw new IllegalArgumentException("Unsupported scheme: " + scheme);
JarURLConnection con = (JarURLConnection) url.openConnection();
JarFile archive = con.getJarFile();
/* Search for the entries you care about. */
Enumeration<JarEntry> entries = archive.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("com/y/app/")) {
...
}
}
You can do the same thing with resources "exploded" on the file system, or in many other repositories, but it's not quite as easy. You need specific code for each URL scheme you want to support.
In general can't get a list of resources like this. Some classloaders may not even be able to support this - imagine a classloader which can fetch individual files from a web server, but the web server doesn't have to support listing the contents of a directory.
For a jar file you can load the contents of the jar file explicitly, of course.
(This question is similar, btw.)
The most robust mechanism for listing all resources in the classpath is currently to use this pattern with ClassGraph, because it handles the widest possible array of classpath specification mechanisms, including the new JPMS module system. (I am the author of ClassGraph.)
List<String> resourceNames;
try (ScanResult scanResult = new ClassGraph()
.whitelistPaths("com/yourcompany/yourapp")
.scan()) {
resourceNames = scanResult.getAllResources().getNames();
}
I've been looking for a way to list the contents of a jar file using the classloaders, but unfortunately this seems to be impossible. Instead what you can do is open the jar as a zip file and get the contents this way. You can use standard (here) ways to read the contents of a jar file and then use the classloader to read the contents.
I usually use
getClass().getClassLoader().getResourceAsStream(...)
but I doubt you can list the entries from the classpath, without knowing them a priori.

Categories

Resources