Best international alternative to Java's getClass().getResource()
I have a lot of resource files bundled with my Java app. These files have filenames containing international characters like ü or æ. I would like to load these files using getClass().getResource(), but apparently this is not supported since for these particular file names, the getResource method always returns null.
That made me experiment with using URL encoding of the international characters, but this is not supported either as stated by http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4968789.
So, my question is: What is the recommended way of loading a resource which has a name containing international characters? For example, I need to load the UTF-8 contents of a file named Sjælland.txt
Not sure if there is a best
(it is probably a candidate for worst
because it is quite a hack) but this seems like a capable mechanism. It sidesteps the need to use getResource
by reading the jar directly.
public class NavelGazing {
public static void main(String[] args) throws Throwable {
// Do a little navel gazing.
java.net.URL codeBase = NavelGazing.class.getProtectionDomain().getCodeSource().getLocation();
// Must be a jar.
if (codeBase.getPath().endsWith(".jar")) {
// Open it.
java.util.jar.JarInputStream jin = new java.util.jar.JarInputStream(codeBase.openStream());
// Walk the entries.
ZipEntry entry;
while ((entry = jin.getNextEntry()) != null ) {
System.out.println("Entry: "+entry.getName());
}
}
}
}
I added a file called Sjælland.txt
and this did successfully get the entry.
I am not sure that I understand you correctly, but if I try
URL url = Test.class.getResource("/Sjælland.txt");
Object o = url.getContent();
then o
is a sun.net.www.content.text.PlainTextInputStream
.
I'm using JDK 1.6 on a Windows machine. I've got (default?) System.property sun.jnu.encoding set to Cp1252. So it all seems to work fine. The bug you've posted seems to be JDK 1.4. It might be what you're using.
链接地址: http://www.djcxy.com/p/11322.html上一篇: Android:我需要关闭游标对象吗?