扩展 InputStream 的 inputStream new class

inputStream new class that extends InputStream

我创建了一个新的 class,它扩展了 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[]) 呼叫 (MyDecompressorInputStream.)read()

此外,您可能已经委托in:

@Override
public int read() throws IOException {
    return in.read();
}

@Override
public void close() throws IOException {
    return in.close();
}

您可能想要扩展 FilterInputStream

一般来说,压缩 GzipInputStream 很好(.gz 格式)。

您是否需要子类化 InputStream? None 中的代码利用了您实现中添加的任何代码。但是,您应该在您的实现中实现 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()

}