InputStream.available()生成Null指针异常

时间:2018-02-15 16:05:12

标签: java nullpointerexception inputstream

我正在尝试构建一个HTTP服务器,我搜索网络来解决这个问题,但我没有找到类似的东西。

我正在尝试自定义输入流以直接从输入流调整读取请求和HTTP响应。实现生成空指针异常的接口的类如下(n = in.available ();):

public class MyHTTPInputStream extends HTTPInputStream{
 public InputStream in = null;
 public String request, reply, dataIn;      // dataIn:= data read from InputStream
 public HTTPMyRequest myRequest;
 public HTTPMyReply myReply;

 public MyHTTPInputStream(InputStream is) {
     super(is);
     // TODO Auto-generated constructor stub
 }

 @Override
 protected void setInputStream(InputStream is) {
     // TODO Auto-generated method stub
     // initialize the variable
     this.in = is;
     request = null;
     reply = null;
     dataIn = null;
 }

 @Override
 public HTTPRequest readHttpRequest() throws HTTPProtocolException {
     request = readFromStream();    // read from inputStream
     System.out.println(request);
     myRequest = new HTTPMyRequest(request);
     return myRequest;
 }

 @Override
 public HTTPReply readHttpReply() throws HTTPProtocolException {
     reply = readFromStream();      // read from inputStream
     myReply = new HTTPMyReply(reply);
     return myReply;
 }

 @Override
 public void close() throws IOException {
     // TODO Auto-generated method stub
     in.close();
 }

 public String readFromStream(){
     // read data from InputStream to String
     int n = 0;
     try {
         n = in.available();  // ******null pointer exception
         System.out.println("n: "+n);
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
     System.out.println("n: "+n);
     byte[] bytes = new byte[n];
     try {
         in.read(bytes, 0, n);
     } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
     String req = new String(bytes, StandardCharsets.UTF_8);
     System.out.println(req);
     return req;
 }
}

在构造函数super(is);中,在接口中引用它:

public HTTPInputStream( InputStream is ) {
        this.setInputStream(is);
    }

这是调用对象的主类(testServer)的一部分:

...
/*
*  TEST INPUTSTREAM
*/
System.out.println("_____HTTP Inputstream_____");
// read HTTP request from file request.txt
InputStream isReq = new FileInputStream(new File("src\\source\\request.txt"));
MyHTTPInputStream myIsReq = new MyHTTPInputStream(isReq);
HTTPMyRequest myRequest =(HTTPMyRequest) myIsReq.readHttpRequest();
System.out.println("_______Read request_______");
...

文件request.txt位于src目录中,是一个包含http请求的简单字符串,我还设法在主屏幕上打印它而没有问题,但是在类readFromStream()中它生成了这个异常(我用......隐藏了路径):

  

_____ HTTP输入流_____

     

线程“main”中的异常java.lang.NullPointerException at   .... MyHTTPInputStream.readFromStream(MyHTTPInputStream.java:59)at   .... MyHTTPInputStream.readHttpRequest(MyHTTPInputStream.java:35)at   .... testServer.main(testServer.java:88)

0 个答案:

没有答案