tuty_fruity
tuty_fruity

Reputation: 547

springboot load a folder as Resource or file inside src/main/resources

i would like to ask how to load a folder as Resource or File in SpringBoot. Let's say i have src/main/resources/testfolder, I want to do something like:

File f = ResourceUtils.getFile("classpath:testfolder");

^ But then that would fail since ResourceUtils can only load actual file(.txt, .csv etc..), not a folder.. Thank you very much in advance..

Edit:

The reason is that i need to get the absolute path of the folder..

File f = ResouceUtils.getFile("classpath:testfolder");
String folderpath = f.getAbsolutePath();

folderpath should be "/workspace/intellij/ProjectName/src/main/resource/testfolder";

Thanks

Upvotes: 0

Views: 1381

Answers (2)

M. Deinum
M. Deinum

Reputation: 125202

As you want to use a temporary directory for testing instead of trying to use Spring classes to obtain a path and shoehorn your test in there use the TemporaryFolder rule from JUnit.

@RunWith(SpringRunner.class)
public class YourTest {

    @Rule
    private TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    public void yourTestMethod() {
        String folder = tempFolder.getRoot();
        when(yourMock.getOutputFolder()).thenReturn(folder);
        // do your thing
        // use tempFolder object to check files/read files etc.
    }

}

Upvotes: 1

Ajith Deivam
Ajith Deivam

Reputation: 766

If you have any folder(for ex: config) under resource folder you should try below i mentioned

File file = ResourceUtils.getFile("classpath:config/test.txt")

Read File Content

String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

Upvotes: 1

Related Questions