How to read a file on the classpath in Java
There are often programming situations when you need to read a file on the classpath via Java. In this article, I will show you how to write code for this. Reading a file on the classpath Let us first take a look at the code that you need to write to read a file on the classpath. public class ReadFileFromClassPathDemo { public static void main(String[] args) throws IOException { // read in the file from the resources directory ClassLoader classLoader = ReadFileFromClassPathDemo.class.getClassLoader(); URL url = classLoader.getResource("input.txt"); String fileName = url.getFile(); File file = new File(fileName); String str = new String(Files.readAllBytes(file.toPath())); System.out.println(str); }} Java has an in-built class called ClassLoader . It is used to dynamically load classes. It can also be used to load resources from the classpath. The code above first obtains a ClassLoader . It then invokes the getResource method on the classLoader . This l