Knowledge
  • Read Me
  • Programming
    • ASP.NET
      • .NET Libraries
      • ASP.NET Core
        • Helper
          • Encryption
          • CSV Helper
          • String Helper
        • Logging
          • Simple Serilog
        • Middlewares
          • IP Restrictions
          • Request Throttling
          • Request Logging
        • Console
          • Command Line with arguments
        • JSON
      • ASP.NET Framework
      • Testing
        • Resources
        • xUnit.net
      • Naming Conventions
      • REST API Guidelines
    • Database
      • SQL Style Guide
      • MSSQL
        • Installation
          • Install MSSQL on MacOS M1 (ARM64)
        • Looping
        • Table Valued Functions
        • Session State
        • SQL Cheat Sheet
        • Export Pipe Delimited CSV With cmdshell
      • Redis
        • Redis Installation on Mac OS
        • Redis Installation on Docker
    • Java
      • AWS SDK - SSM
      • mTLS HTTP Connection
      • Read Resource Files
    • Javascript
      • Javascript Libraries
    • Python
    • OpenSSL
      • One Way SSL & Two Way SSL
      • Common OpenSSL Commands
      • Create Self-Signed Certificate
    • Misc
      • Git Commands
      • Windows Commands
      • PowerShell Commands
      • Vulnerabilities Dependency Check
      • Replace Filename Command
      • JSON Web Token (JWT)
      • Rabbit MQ Message-Broker
      • Pandoc Convert Document
  • DevOps
    • What is DevOps
    • CI & CD
    • Azure DevOps
  • Tools
    • Development Tools
Powered by GitBook
On this page

Was this helpful?

  1. Programming
  2. Java

Read Resource Files

Files in resources folder using Maven Project

In Maven Project, the files located in the src/main/resources

|__src\
      |__main\*.java
      |
      |__resources\
             |__config.json
             |__others.json
package com.example.resources;

public class Main {
  public static void main(String[] args)
  {
    String config = getResourceAsString("config.json");    
    System.out.println(config);
  }
  
  public static String getResourceAsString(String fileName) throws IOException {
    InputStream inputStream = getResourceAsStream(fileName);

    String text = new BufferedReader(
      new InputStreamReader(inputStream, StandardCharsets.UTF_8))
        .lines()
        .collect(Collectors.joining("\n"));

    return text;
  }

  public static InputStream getResourceAsStream(String fileName) {
    // The class loader that loaded the class
    ClassLoader classLoader = Main.class.getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(fileName);

    // the stream holding the file content
    if (inputStream == null) {
      throw new IllegalArgumentException("file not found! " + fileName);
    } else {
      return inputStream;
    }
  }
}
PreviousmTLS HTTP ConnectionNextJavascript

Last updated 2 years ago

Was this helpful?