【问题标题】:springboot load a folder as Resource or file inside src/main/resourcesspringboot 在 src/main/resources 中加载一个文件夹作为资源或文件
【发布时间】:2019-03-11 06:33:15
【问题描述】:

我想问一下如何在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();

文件夹路径应该是“/workspace/intellij/ProjectName/src/main/resource/testfolder”;

谢谢

【问题讨论】:

  • 为什么?你想达到什么目标。
  • 为什么?请解释您要实现的目标...您需要该文件夹来做某事...
  • @M.Deinum 请查看我的编辑。谢谢
  • 为什么需要绝对路径?你还没有回答这个问题。
  • @M.Deinum 我需要文件夹的绝对路径,因为我正在我的项目中进行单元测试。我有一个类(属性类),我需要模拟一个名为 PropertyClass::getOutputDir 的方法,现在我需要模拟它并返回一个文件夹路径。这就是为什么我需要绝对路径。

标签: spring spring-boot


【解决方案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.
    }

}

【讨论】:

    【解决方案2】:

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

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

    读取文件内容

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

    【讨论】:

      猜你喜欢
      • 2017-02-05
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      • 2015-03-22
      • 2014-11-21
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多