如何使用FileInputStream访问jar中的txt文件?

我知道getResourceAsStream()方法但是解析器读取文件存在问题,整个结构实现为期望FileInputStream()getResourceAsStream()返回无法转换的输入流。 对于这种情况,有没有简单的“修复”?

JAR文件中包含的资源本身不是文件,无法使用FileInputStream读取。 如果您的代码绝对需要FileInputStream ,那么您需要使用getResourceAsStream()提取数据,将其复制到临时文件中,然后将该临时文件的FileInputStream传递给您的代码。

当然,将来,永远不要编写代码来期待像InputStream这样的具体实现,你总会后悔的。

我最近遇到了同样的问题。 我们使用的第三方库从FileInputStream读取,但资源可以是JAR或远程中的任何位置。 我们曾经写过临时文件,但是开销太大了。

一个更好的解决方案是编写一个包装InputStream的FileInputStream。 这是我们使用的课程,

 public class VirtualFileInputStream extends FileInputStream { private InputStream stream; public VirtualFileInputStream(InputStream stream) { super(FileDescriptor.in); // This will never be used this.stream = stream; } public int available() throws IOException { throw new IllegalStateException("Unimplemented method called"); } public void close() throws IOException { stream.close(); } public boolean equals(Object obj) { return stream.equals(obj); } public FileChannel getChannel() { throw new IllegalStateException("Unimplemented method called"); } public int hashCode() { return stream.hashCode(); } public void mark(int readlimit) { stream.mark(readlimit); } public boolean markSupported() { return stream.markSupported(); } public int read() throws IOException { return stream.read(); } public int read(byte[] b, int off, int len) throws IOException { return stream.read(b, off, len); } public int read(byte[] b) throws IOException { return stream.read(b); } public void reset() throws IOException { stream.reset(); } public long skip(long n) throws IOException { return stream.skip(n); } public String toString() { return stream.toString(); } } 

不要相信你的解析只适用于FileInputStream而不适用于InputStream

如果这是真实的情况,你必须使用该解析器

2个选项

  1. 使用适配器模式创建CustomFileInputStream并覆盖相应的方法,更多的是将getResourceAsStream数据重定向到CustomFileInputStream

  2. 将你的getResourceAsStream保存到临时文件中,并解析临时文件,完成后删除该文件