top*_*ess 6 java inputstream fileinputstream
我知道这个getResourceAsStream()方法,但解析器读取文件存在问题,整个结构实现为期望a FileInputStream()并getResourceAsStream()返回无法转换的输入流.对于这种情况,有没有简单的"修复"?
ska*_*man 20
JAR文件中包含的资源本身不是文件,无法使用a读取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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10112 次 |
| 最近记录: |