spring boot将文件夹作为资源或文件加载到src / main / resources中

问题描述 投票:0回答:2

我想问一下如何在SpringBoot中将文件夹加载为Resource或File。假设我有src / main / resources / testfolder,我想做类似的事情:

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

^然后那会失败,因为ResourceUtils只能加载实际文件(.txt,.csv等..),而不是文件夹..非常感谢你提前..

编辑:

原因是我需要获取文件夹的绝对路径..

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

folderpath应为“/ workspace / intellij / ProjectName / src / main / resource / testfolder”;

谢谢

spring spring-boot
2个回答
1
投票

由于您希望使用临时目录进行测试而不是尝试使用Spring类来获取路径并在那里使用来自JUnit的TemporaryFolder规则进行测试。

@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.
    }

}

1
投票

如果你在资源文件夹下有任何文件夹(例如ex:config),你应该尝试下面我提到的

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

阅读文件内容

String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
© www.soinside.com 2019 - 2024. All rights reserved.