Example:
The file is located in resources/asq-1.json
// absolute path
// String filePath = "/Users/dph/Documents/work-web-nginx/pte/pte-backend/src/main/resources/asq-1.json";
// relative path (to pte-backend)
String filePath = "src/main/resources/asq-1.json";
// check what path is
File f = new File(filePath);
System.out.println(f.getAbsolutePath());
try {
// Creates a FileReader with default encoding
FileReader input1 = new FileReader(filePath);
// Returns the character encoding of the file reader
System.out.println("Character encoding of input1: " + input1.getEncoding());
// Closes the reader
input1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Method 2: just directly put asq-1.json
as fileName
String fileName = "asq-1.json";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
System.out.println(file.getAbsolutePath());
try {
// Creates a FileReader with default encoding
FileReader input1 = new FileReader(classLoader.getResource(fileName).getFile());
// Returns the character encoding of the file reader
System.out.println("Character encoding of input1: " + input1.getEncoding());
// Closes the reader
input1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
In this case, asq-1.json will be copied to target/classes and the absolute path is /Users/dph/Documents/work-web-nginx/pte/pte-backend/target/classes/asq-1.json
Thread.currentThread().getContextClassLoader()
has the benefit of not needing to be changed depending on whether you’re calling from a static or instance method.