我做了一个扩展InputStream的新类,它必须@Override read().
我正在尝试使用方法read(int b),但是当我使用它时,它将转到该方法
read(),我不能使用参数,我通过了.
这是我的代码:
public class Run {
public static void main(String[] args) {
DFSMaze3dGenerator mg = new DFSMaze3dGenerator();
try {
Maze3d maze3d = mg.generate(1, 5, 5);
maze3d.print3DMaze();
OutputStream out = new MyCompressorOutputStream(
new FileOutputStream("1.maz"));
out.write(maze3d.toByteArray());
byte[] arr = maze3d.toByteArray();
System.out.println("");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
out.close();
InputStream in = new MyDecompressorInputStream(new FileInputStream(
"1.maz"));
byte b[] = new byte[maze3d.toByteArray().length];
in.read(b);
in.close();
Maze3d loaded = new Maze3d(b);
System.out.println(loaded.equals(maze3d));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
使用方法时如何使用参数:read(b);
???
public class MyDecompressorInputStream extends InputStream {
InputStream in;
int count;
boolean even = false;
public MyDecompressorInputStream(InputStream in) {
super();
this.in = in;
}
@Override
public int read() throws IOException {
return 100;
}
}
解决方法:
您是否有必要将InputStream子类化?主程序中的任何代码都不会利用实现中添加的任何代码.但是,您应该在实现中实现read(byte []).这是适用于我的机器的类似实现.
class MyInputStream extends InputStream {
InputStream in;
int count;
boolean even = false;
public MyInputStream(InputStream stream){
this.in = stream;
}
@Override
public int read() throws IOException {
return this.in.read();
}
@Override
public int read(byte[] toStore) throws IOException {
return this.in.read(toStore);
}
}
和我的主要使用类似:
public static void main(String[] args){
MyInputStream stream = new MyInputStream(new ByteArrayInputStream(new byte[] {0, 0, 1}));
byte[] storage = new byte[3];
try {
stream.read(storage);
for (int i = 0; i < storage.length; ++i){
System.out.println(storage[i]); //0 0 1
}
} catch (IOException e) {
e.printStackTrace();
}
stream.close()
}