英文:
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云函数中使用了FileReader
和BufferedReader
:
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");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论