Get Path to Subdirectory in Resources Folder

Get Path to Subdirectory in Resources Folder

Just solved it.

NSBundle *mainBundle = [NSBundle mainBundle];
NSArray *pngs = [mainBundle pathsForResourcesOfType:@".png"
inDirectory:@"random pictures"];

NSLog(@"pngs in my dir:%@", pngs);

dir structure: "Resources/random pictures".

This works, BUT, when you add the files to 'Resources', you need to check "Create folder references for any aded folders", and NOT "Create groups for any added folders".

important step

Cheers!

Loading files from subfolder of the resources folder in Java

I am not sure why your version is not working but here is what I use:

getClass().getResourceAsStream("/img/favicon.png");

Note: '/' in "/img" is necessary if your class is not in a default package
(which it should not be)

iPhone : Get the file path which is within subfolder of Resource folder

To continue psychotiks answer a full example would look like this:

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
NSString *filePath = nil;

if (filePath = [thisBundle pathForResource:@"Data" ofType:@"txt" inDirectory:@"Folder1"]) {

theContents = [[NSString alloc] initWithContentsOfFile:filePath];

// when completed, it is the developer's responsibility to release theContents

}

Notice that you can use -pathForResource:ofType:inDirectory to access ressources in sub directories.

How to get the path of src/test/resources directory in JUnit?

Try working with the ClassLoader class:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

A ClassLoader is responsible for loading in classes. Every class has a reference to a ClassLoader. This code returns a File from the resource directory. Calling getAbsolutePath() on it returns its absolute Path.

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

Read files from sub directories of class path resource folder in spring boot

As mentioned in the question, first I want to get confX directories then read conf.txt files.

Finally, I could solve my issue as below.

ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
try {
Resource resources[] = resolver.getResources("classpath:Conf/*/");
} catch (IOException e) {
e.printStackTrace();
}

This will give all sub directories of Conf directory. Here / at the end in classpath:Conf/*/ is very important. If we do not give / it will work normally but will not work in jar.
From the above code block resources[] array will contains directory location like this class path resource [Conf/conf1/] and so on. I need sub directory name to read corresponding file. Here is the code for it.

Arrays.asList(resources).stream()
.forEach(resource ->{
Pattern dirPattern = Pattern.compile(".*?\\[(.*/(.*?))/\\]$");
if (resource.toString().matches(".*?\\[.*?\\]$")) {
Matcher matcher = dirPattern.matcher(resource.toString());
if (matcher.find()) {
String dir = matcher.group(1);
readFile(dir);
}
}
});

public void readFile(String dir)
{

ClassPathResource classPathResource = new ClassPathResource(dir+ "/conf.txt");
try (BufferedReader fileReader = new BufferedReader(
new InputStreamReader(classPathResource2.getInputStream()))) {
fileReader.lines().forEach(data -> System.out.println(data));
}catch (IOException e) {
e.printStackTrace();
}
}

I need to map each txt file with its corresponding directory. That is why I approached this way. If you just need to get files and read you can do it like below. This will list everything under Conf directory.

 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
try {
Resource resources[] = resolver.getResources("classpath:Conf/**");
} catch (IOException e) {
e.printStackTrace();
}

In Python, how do I get the path to a directory of files located within a module

EDIT [2022-01-12]:

I updated my approach with a much simpler solution using pathlib.Path(__file__), which returns the full PosixPath to the file in the package directory, and from there it's easy to navigate to the desired subdirectory. This was much easier, it didn't require additional packages installed, and works just fine for me with Python 3.6 - 3.10

I put the following in __init__.py

import subprocess
from pathlib import Path
p = Path(__file__)
sounds_dir = p.parent / 'sounds'

def beep(sound=2):
sounds = [x for x in sounds_dir.iterdir()]
return_code = subprocess.call(['afplay', sounds[sound]])

To use, I made sure to add the finished package (renamed to beepr) to my PYTHONPATH and I've had no issues using it like so:

from beepr import beep
beep(2)

Here's the (previous) solution I'd used that needed importlib.resources and worked with Python 3.7 & 3.8, or the backport importlib_resources to work with < 3.7

# py 3.7
import os, subprocess
from importlib.resources import path

def play(sound=0):
with path('playr', 'sounds') as sounds_path:
sounds = os.listdir(sounds_path)
audio_file = os.path.join(sounds_path, sounds[sound])
return_code = subprocess.call(['afplay', audio_file])

But again, besides being less straightfoward, it also didn't work with Python 3.9 or 3.10


How to get path to a subfolder in main bundle?

In Swift-3 make URL, and call appendingPathComponent:

let resourcePath = Bundle.main.resourcePath
let subdir = URL(fileURLWithPath:resourcePath!).appendingPathComponent("sub").path

or simply

let subdir = Bundle.main.resourceURL!.appendingPathComponent("sub").path

(thanks, Martin R!)

See this Q&A on information on stringByAppendingPathComponent method in Swift.

How to add a subfolder in resources in Maven

You don't need to add the subfolder abc to your pom. Since text.txt is in the abc folder, you would access it like this:

InputStream in = getClass().getResourceAsStream("/abc/text.txt");



Related Topics



Leave a reply



Submit