How to Read Resource Files in Java

How to Read Resource Files in Java

In this example you will learn about how to read resource files in java. This example program has been tested and output shared in the same post.

Project Structure

How to Read Resource Files in Java

Reading resource file using Java

package com.dineshkrish;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Example {

	public static void main(String[] args) {

		// creating class loader object
		ClassLoader loader = ClassLoader.getSystemClassLoader();

		try {

			// getting the resource and converting it as file object
			File file = new File(loader.getResource("sample.txt").toURI());

			// checking is exist or not?
			if (file.exists()) {

				System.out.println("The file is exist...");
			} else {

				System.out.println("The file is not exist...");
			}

		} catch (URISyntaxException e) {

			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}
}

Output

The file is exist...

References

1. ClassLoader Class
2. public static URL getSystemResource(String name) Method