我正在尝试扩展InputStream类并使用自定义的read()方法。 这是我的班级快照:
class MyClass
{
/** Input stream */
private final MyInputStream in = new MyInputStream();
/**get the InputStream
public InputStream getInputStream()
{
return in;
}
/** Inner class for MyInputStream */
class MyInputStream extends InputStream
{
//here i am keeping implementation of read methods
public synchronized int read( byte b[] ) throws IOException
{
//..................
}
}
}
这是我的客户端类
public class MyClient {
//InStreams
protected BufferedInputStream mBufInStream;
protected DataInputStream mInStream;
public int read(byte[] buffer)
{
MyClass obj1 = new MyClass();
mBufInStream = new BufferedInputStream(obj1.getInputStream());
mInStream = new DataInputStream(mBufInStream);
try
{
int i = mBufInStream.read(buffer);
return i;
}
catch (IOException ex)
{
return -1;
}
}
public static void main(String args[])
{
MyClient cl1 = new MyClient();
int ret = 0;
byte[] data = {};
ret = cl1.read(data);
}
}
我想要做的是在完成cl1.read时调用MyInputStream类的read方法。
我不知道我在这里失踪了什么。
答案 0 :(得分:1)
我使用MyInputStream创建了DataInputStream对象并使其正常工作。这是更新的代码:
public class MyClient {
//InStreams
protected DataInputStream mInStream;
public int read(byte[] buffer)
{
MyClass obj1 = new MyClass();
mInStream = new DataInputStream(obj1.getInputStream());
try
{
int i = mInStream.read(buffer);
return i;
}
catch (IOException ex)
{
return -1;
}
}
public static void main(String args[])
{
MyClient cl1 = new MyClient();
int ret = 0;
byte[] data = {};
ret = cl1.read(data);
}
}
答案 1 :(得分:0)
如果要扩展输入流类,则需要为以下方法提供具体定义:
public abstract int read() throws IOException
您的类具有读取方法,签名为:
public int read(byte[] b) throws IOException
因此除了read()
之外,请实施read(byte[] b)
。我做了一些修改,它现在有效......
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
public class MyClient {
//InStreams
protected BufferedInputStream mBufInStream;
protected DataInputStream mInStream;
public int read(byte[] buffer) {
MyClass obj1 = new MyClass();
// mBufInStream = new BufferedInputStream(obj1.getInputStream());
// mInStream = new DataInputStream(mBufInStream);
try {
int i = obj1.getInputStream().read(buffer);
return i;
} catch (IOException ex) {
return -1;
}
}
public static void main(String args[]) {
MyClient cl1 = new MyClient();
int ret = 0;
byte[] data = {'a','b'};
ret = cl1.read(data);
System.out.println(ret);
}
}
import java.io.IOException;
import java.io.InputStream;
class MyClass {
/** Input stream */
private final MyInputStream in = new MyInputStream();
//get the InputStream
public InputStream getInputStream() {
return in;
}
class MyInputStream extends InputStream {
//here i am keeping implementation of read methods
public int read( byte b[] ) throws IOException {
System.out.println("Inside my read()");
return b.length;
//..................
}
@Override
public int read() throws IOException {
// TODO Auto-generated method stub
return 0;
}
}
}