refactor: Make FileResClassLoader usable for other file paths.

This commit is contained in:
Ben Woo 2023-02-28 22:55:18 +08:00
parent ffc4c600c5
commit 560e3ab201
No known key found for this signature in database
GPG Key ID: FB2A3645536E12C8
2 changed files with 9 additions and 10 deletions

View File

@ -13,21 +13,17 @@ import org.bukkit.plugin.Plugin;
* A class loader that loads resources from the plugin's locales folder. * A class loader that loads resources from the plugin's locales folder.
*/ */
public class FileResClassLoader extends ClassLoader { public class FileResClassLoader extends ClassLoader {
private static final String DEFAULT_LOCALE_FOLDER_PATH = "locales";
private final transient File localesFolder;
public FileResClassLoader(final Plugin plugin) { private final transient File targetFolder;
this(plugin, DEFAULT_LOCALE_FOLDER_PATH);
}
public FileResClassLoader(final Plugin plugin, final String localesFolderPath) { public FileResClassLoader(final Plugin plugin, final String subFolder) {
super(plugin.getClass().getClassLoader()); super(plugin.getClass().getClassLoader());
this.localesFolder = new File(plugin.getDataFolder(), localesFolderPath); this.targetFolder = new File(plugin.getDataFolder(), subFolder);
} }
@Override @Override
public URL getResource(final String string) { public URL getResource(final String string) {
final File file = new File(localesFolder, string); final File file = new File(targetFolder, string);
if (file.exists()) { if (file.exists()) {
try { try {
return file.toURI().toURL(); return file.toURI().toURL();
@ -39,7 +35,7 @@ public class FileResClassLoader extends ClassLoader {
@Override @Override
public InputStream getResourceAsStream(final String string) { public InputStream getResourceAsStream(final String string) {
final File file = new File(localesFolder, string); final File file = new File(targetFolder, string);
if (file.exists()) { if (file.exists()) {
try { try {
return new FileInputStream(file); return new FileInputStream(file);

View File

@ -6,12 +6,15 @@ import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
public class PluginLocales extends BukkitLocales { public class PluginLocales extends BukkitLocales {
private static final String DEFAULT_LOCALE_FOLDER_PATH = "locales";
public PluginLocales(BukkitCommandManager manager) { public PluginLocales(BukkitCommandManager manager) {
super(manager); super(manager);
} }
public boolean addFileResClassLoader(@NotNull Plugin plugin) { public boolean addFileResClassLoader(@NotNull Plugin plugin) {
return this.addBundleClassLoader(new FileResClassLoader(plugin)); return this.addBundleClassLoader(new FileResClassLoader(plugin, DEFAULT_LOCALE_FOLDER_PATH));
} }
public boolean addFileResClassLoader(@NotNull Plugin plugin, @NotNull String localesFolderPath) { public boolean addFileResClassLoader(@NotNull Plugin plugin, @NotNull String localesFolderPath) {