Java: Place the ResourceBundle properties file anywhere

Introduction

I ended up using ResourceBundle when using Locate in Java.

Therefore, when the properties file for ResourceBundle was placed in the resource directory, an error (java.util.MissingResourceException) occurred that the target file could not be found, so a memorandum for placing the puroperties file in any location is shown below. leave.

environment

** ▼ Directory structure **

image.png

In Main.java, I prepared Locales from Japan and the United States and placed the properties files for each locale directly under the resource directory, but I was told that the properties files could not be found.

The cause is that the classpath could not be referenced below.

By the way, the above can be confirmed by the following description.

Main.java



class Main {
	public static void main(String[] args) {
        System.out.println(System.getProperty("java.class.path"));
}

As an aside, in order to read the properties file with the above classpath, it is necessary to place it directly under the main directory.

To place the properties file anywhere and refer to it

In conclusion, use ʻURLClassLoader`.

Main.java


class Main {
	public static void main(String[] args) throws MalformedURLException {

        File dicDir = Paths.get(".\\resource").toFile(); // ★1

        URLClassLoader urlLoader; // ★2
        urlLoader = new URLClassLoader(new URL[]{dicDir.toURI().toURL()}); // ★3

		Locale localeJp = Locale.JAPAN;
		Locale localeUs = Locale.US;

		List<Locale> locales =
				new ArrayList<Locale>(Arrays.asList(localeJp, localeUs));

		for (Locale locale : locales) {
			ResourceBundle rb =
					ResourceBundle.getBundle("Source" ,locale ,urlLoader); // ★4

			System.out.println(rb.getString("apple") + rb.getString("orange"));

		}
	}
}

The procedure to refer to the properties file placed in an arbitrary location is as follows.

  1. Specify the location to place the properties file in ★ 1.
  2. Create an instance of the class loader specified by 1 in ★ 2 and ★ 3.
  3. Refer to the properties file whose base name is Source in ★ 4.

Now you can refer to the properties file in any location by changing the path of ★ 1.

review

Recommended Posts

Java: Place the ResourceBundle properties file anywhere
Read Java properties file in C #
Unzip the zip file in Java
[Java] How to use the File class
[Java8] Search the directory and get the file
JAVA: jar, aar, view the contents of the file
About the description order of Java system properties
[JAVA] Get only the file name, excluding the extension
[Java] Read the file in src / main / resources
java file creation
[Java] How to extract the file name from the path
[Java] File system operation
Read Java Property file
java (split source file)
java core: chopped core file
Put the file in the properties of string in spring xml configuration
About the behavior when doing a file map with java
A memorandum to reach the itchy place for Java Gold