Skip to content
Advertisement

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

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

Advertisement

Answer

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:

4 People found this is helpful
Advertisement