Load File From Resources Folder Java
In this tutorial we will show you how to load a file from the resources folder in Java. There are some cases in which you want to get a file from the resources folder, in particular when you want to unit test certain code that does file manipulations e.g.: creating zip files, reading input files etc, … There are two ways you can get the file from the resources folder.
File from resources folder with getResource()
Class.getResource
can take a “relative” resource name, which is treated relative to the class’s package. Alternatively you can specify an “absolute” resource name by using a leading slash. This method delegates the call to its class loader. After making these changes to the resource name: if the resource name starts with “/”, it is unchanged; otherwise, the package name is prepended to the resource name after converting “.” to “/”. If this object was loaded by the bootstrap loader, the call is delegated to ClassLoader.getSystemResource().
File file = new File(getClass().getResource("/example.txt").getFile());
File from resources folder with ClassLoader
ClassLoader resource paths are always deemed to be absolute.
File file = new File(getClass().getClassLoader().getResource("example.txt").getFile());
How to I read the content from loaded file & update data??
Lets in my file i have 1 line (Name: XYZ) And I want to update it to “Name = ABC”, How can i achieve this??