0

I am trying to read values from a json file which I have placed in my resource folder directly. I am able to run it successfully without any error in bootrun & also build successfully within IntelliJ with the below code

 try (FileInputStream serviceAccountStream=new FileInputStream("src/main/resources/mockData.json");) {
            credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch (Exception e){
            System.out.println("Issue with the credential reader"+e.getMessage());

        }

However when a JAR is created with the above, I am getting exception as fileNotFound

java -jar app-0.0.1-SNAPSHOT-plain.jar

java.io.FileNotFoundException: src\main\resources\mockData.json (The system cannot find the path specified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at java.io.FileInputStream.<init>(Unknown Source)
        at com.exampleBQ.demoBQ.BQConfig.getBQBean(BQConfig.java:31)
    ```

Could someone plz help on how to read the file as FileInputStream  within Jar
PotatoGod
  • 15
  • 3
  • You don't. You use `Class.getResource()` and friends. You don't have any actual need in this code for `FileInputStream` specifically. – user207421 Apr 13 '22 at 00:00
  • 1
    Thanks @user207421 for your valuable input This worked for me: InputStream in = getClass().getResourceAsStream("/mockData.json"); – PotatoGod Apr 13 '22 at 04:25
  • Resource resource = new ClassPathResource("classpath:data.txt"); File file = resource.getFile(); String content = new String(Files.readAllBytes(file.toPath())); – Lewis Florez R Jan 19 '23 at 11:41

1 Answers1

0

As you are using Springboot you can use Resource abstraction

Try doing this:-

@Value("classpath:mockData.json")
Resource resourceFile;
James S
  • 60
  • 3
Subhash Rawat
  • 451
  • 6
  • 13