Reputation: 734
I made a new class that extends InputStream and has to @Override read(). I am trying to use the method read(int b), but when I use it,it goes to the method read() and I cant use the parameter,I passed over.
Here is my code:
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();
}
}
}
How can i use the parameter when i use the method: 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;
}
}
Upvotes: 4
Views: 5118
Reputation: 66
Is there a reason you need to subclass InputStream? None of the code in your main leverages any added code in your implementation. However, you should implement read(byte[]) in your implementation. This is a similar implementation that works on my machine.
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);
}
}
and my main uses this similarly:
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()
}
Upvotes: 5
Reputation: 109597
InputStream.read(byte[])
calls (MyDecompressorInputStream.
)read()
Furthermore you probably already delegate to in
:
@Override
public int read() throws IOException {
return in.read();
}
@Override
public void close() throws IOException {
return in.close();
}
You might want to extend FilterInputStream instead.
In general for compression GzipInputStream is nice (.gz format).
Upvotes: 0