gpt4 book ai didi

java - inputStream 扩展 InputStream 的新类

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:41:58 29 4
gpt4 key购买 nike

我创建了一个扩展 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);
}
}

和我的 main 类似地使用它:

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()

}

关于java - inputStream 扩展 InputStream 的新类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32442435/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com