[英]File list from classpath directory in running jar
我想从类路径中加载所有资源包属性,以便可以显示支持的语言。 我从这里获得了参考,并尝试了第一种解决方案。 当我从Eclipse运行代码时,它可以工作。 但是,当我创建可执行jar文件时,它无法读取文件。 我不知道为什么从命令java -jar AppName.jar
运行时行为会有所不同
我的代码是:
public static List<String> getResourceFiles(String path) throws IOException
{
List<String> filenames = new ArrayList<>();
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println("br = " + br.readLine());
String resource;
while ((resource = br.readLine()) != null)
{
filenames.add(resource);
}
return filenames;
}
private static InputStream getResourceAsStream(String resource)
{
final InputStream in = getContextClassLoader().getResourceAsStream(resource);
System.out.println("input stream = " + in);
return in == null ? FileUtil.class.getResourceAsStream(resource) : in;
}
private static ClassLoader getContextClassLoader()
{
return Thread.currentThread().getContextClassLoader();
}
在这里,我注意到从命令运行时InputStream为null,但是从Eclipse运行时InputStream不为null。
如何解决此问题,以便从命令运行时也可以读取资源文件?
我找到了解决方案。 下面的代码为我工作:
public static String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException
{
URL dirURL = clazz.getClassLoader().getResource(path);
if (dirURL != null && dirURL.getProtocol().equals("file"))
{
/* A file path: easy enough */
return new File(dirURL.toURI()).list();
}
if (dirURL == null)
{
/*
* In case of a jar file, we can't actually find a directory. Have to assume the
* same jar as clazz.
*/
String me = clazz.getName().replace(".", "/") + ".class";
dirURL = clazz.getClassLoader().getResource(me);
}
if (dirURL.getProtocol().equals("jar"))
{
/* A JAR path */
String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); // strip out only the JAR file
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar
Set<String> result = new HashSet<String>(); // avoid duplicates in case it is a subdirectory
while (entries.hasMoreElements())
{
String name = entries.nextElement().getName();
if (name.startsWith(path))
{ // filter according to the path
String entry = name.substring(path.length());
int checkSubdir = entry.indexOf("/");
if (checkSubdir >= 0)
{
// if it is a subdirectory, we just return the directory name
entry = entry.substring(0, checkSubdir);
}
result.add(entry);
}
}
return result.toArray(new String[result.size()]);
}
throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}
我认为您可以将应用程序路径添加到系统环境(类路径),如果无法解决问题,请在初始化文件流并修复它之前尝试打印真实路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.