Unable to locate file when code moved to CloudHub

374 views Asked by At

Usecase: Reading File contents in Java (Deployed at cloud-hub).

Problem: I have written a java class which reads file and contents are log to console.But if same code is moved to cloud Hub, File-not-Found exception is raised.

Question: I understand that src/main/resources folder structure will not be available,what should be the location of file to be used while creating the File instance if code is running through cloudhub

Here is the code snippet works only in Local environment.

package com.testUtil;

import org.mule.api.MuleEventContext;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.mule.api.lifecycle.Callable;

public class TestClass implements Callable {

    @Override
    public Object onCall(MuleEventContext eventContext) throws Exception {

        System.out.println("Files and directories present at src/main/resources are :");

            File folder = new File("./src/main/resources/");
            File[] listOfFiles5 = folder.listFiles();

            for (int i = 0; i < listOfFiles5.length; i++) {
              if (listOfFiles5[i].isFile()) {
                System.out.println("File " + listOfFiles5[i].getName());
              } else if (listOfFiles5[i].isDirectory()) {
                System.out.println("Directory " + listOfFiles5[i].getName());
              }
            }

        System.out.println("expected output is: xsd");


        FileReader fr = new FileReader(folder+"/xsd/Request.xsd"); 
        BufferedReader br = new BufferedReader(fr); 
        String contents=""; 
        String s=""; 
        while((s = br.readLine()) != null) { 

            contents+=s;
        } 
        System.out.println(contents);
        fr.close(); 


        return contents;
    }

}

But

   this.getClass().getResource("./").getPath();

gives ./mule-3.4.1-R35/conf as output.

So was trying with below snnipet,but still FileNotFoundException

FileReader fr = new FileReader(this.getClass().getResource("./").getPath()+"/xsd/Request.xsd");

Please Help !! Thanks

1

There are 1 answers

0
David Dossot On

Files in src/main/resources should be loaded with the classpath, not as files.

I recommend using Reflections for scanning the classpath efficiently.