猿问

我如何从jar文件中获取资源“文件夹”?

我在项目的根目录中有一个资源文件夹/程序包,我“不想”加载某个文件。如果我想加载某个文件,我将使用class.getResourceAsStream,我会很好的!我实际上要做的是在资源文件夹中加载“文件夹”,循环访问该文件夹中的文件,并获取每个文件的流,并读取内容...假定在运行时之前未确定文件名... 我该怎么办?有没有办法获取jar文件中“文件夹”中文件的列表?请注意,带有资源的JAR文件与从中运行代码的JAR文件相同。



智慧大石
浏览 605回答 3
3回答

慕码人8056858

在尝试从jar中打包的资源中加载某些hadoop配置时,我手头也遇到了同样的问题……在IDE和jar(发行版)上。我发现java.nio.file.DirectoryStream最好的方法是遍历本地文件系统和jar上的目录内容。String fooFolder = "/foo/folder";....ClassLoader classLoader = foofClass.class.getClassLoader();try {&nbsp; &nbsp; uri = classLoader.getResource(fooFolder).toURI();} catch (URISyntaxException e) {&nbsp; &nbsp; throw new FooException(e.getMessage());} catch (NullPointerException e){&nbsp; &nbsp; throw new FooException(e.getMessage());}if(uri == null){&nbsp; &nbsp; throw new FooException("something is wrong directory or files missing");}/** i want to know if i am inside the jar or working on the IDE*/if(uri.getScheme().contains("jar")){&nbsp; &nbsp; /** jar case */&nbsp; &nbsp; try{&nbsp; &nbsp; &nbsp; &nbsp; URL jar = FooClass.class.getProtectionDomain().getCodeSource().getLocation();&nbsp; &nbsp; &nbsp; &nbsp; //jar.toString() begins with file:&nbsp; &nbsp; &nbsp; &nbsp; //i want to trim it out...&nbsp; &nbsp; &nbsp; &nbsp; Path jarFile = Paths.get(jar.toString().substring("file:".length()));&nbsp; &nbsp; &nbsp; &nbsp; FileSystem fs = FileSystems.newFileSystem(jarFile, null);&nbsp; &nbsp; &nbsp; &nbsp; DirectoryStream<Path> directoryStream = Files.newDirectoryStream(fs.getPath(fooFolder));&nbsp; &nbsp; &nbsp; &nbsp; for(Path p: directoryStream){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream is = FooClass.class.getResourceAsStream(p.toString()) ;&nbsp; &nbsp; &nbsp; &nbsp; performFooOverInputStream(is);&nbsp; &nbsp; &nbsp; &nbsp; /** your logic here **/&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }catch(IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; throw new FooException(e.getMessage());&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }}else{&nbsp; &nbsp; /** IDE case */&nbsp; &nbsp; Path path = Paths.get(uri);&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path);&nbsp; &nbsp; &nbsp; &nbsp; for(Path p : directoryStream){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InputStream is = new FileInputStream(p.toFile());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; performFooOverInputStream(is);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (IOException _e) {&nbsp; &nbsp; &nbsp; &nbsp; throw new FooException(_e.getMessage());&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答