繁体   English   中英

如何从 GCP Cloud Function 中的 maven 资源文件夹中读取文件?

[英]How to read a file from maven resources folder in GCP Cloud Function?

我的项目使用 Maven 和默认文件夹结构,当我的Google Cloud Function试图从资源目录 ( src/main/resources ) 读取 JSON 文件时,它失败了:

找不到文件异常

下面是我的代码,它是从类路径资源文件夹中读取的标准代码。

任何提示可能是错的?

ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource("gcs-sf-dump.sql");
if (resource == null) {
    throw new IllegalArgumentException("file is not found!");
} else {
    File myFile =  new File(resource.getFile());
    String query = FileUtils.readFileToString(myFile);
}

我在我的 GCP Cloud Functions 中使用FileReaderBufferedReader

try (FileReader fileReader = new FileReader("src/main/resources/myFile.sql"); 
 BufferedReader bufferedReader = new BufferedReader(fileReader)) {
   String fileContent = bufferedReader.lines()
                                   .collect(Collectors.joining(System.lineSeparator()));
}

使用来自IOUtils Commons ( org.apache.commons.io.IOUtils ) 的 IOUtils:

String fileContent = IOUtils.toString(getClass().getClassLoader()
       .getResourceAsStream("src/main/resources/myFile.sql"), StandardCharsets.UTF_8);

我用getResourceAsStream尝试了一些测试,但没有成功!


参考:

对我来说这有效:

 java.io.File filePath = new java.io.File("src/main/resources/file.sql");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM