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

huangapple go评论76阅读模式
英文:

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("文件未找到!");
} else {
    File myFile =  new File(resource.getFile());
    String query = FileUtils.readFileToString(myFile);
}
英文:

My project uses Maven with the default folder structure and when my Google Cloud Function is trying to read a JSON file from the resources directory (src/main/resources), it fails with:

> File Not Found Exception

Below is my code which is standard to read from the classpath resources folder.

Any hints what could be wrong?

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);
}

答案1

得分: 2

我在我的GCP云函数中使用了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()));
}

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

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

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

参考链接:

英文:

I use a FileReader with BufferedReader in my GCP Cloud Functions:

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

Using IOUtils from Apache Commons (org.apache.commons.io.IOUtils):

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

> I tried some tests with getResourceAsStream but no success!


Reference:

答案2

得分: 1

以下是翻译好的内容:

对于我来说,这个是有效的:

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

For me this works:

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

huangapple
  • 本文由 发表于 2020年9月21日 19:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63991598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定