0

示例.java

class Sample
{
    private BufferedOutputStream output;

    public handleRequest(Socket socket)
    {
        this.output = new BufferedOutputStream(socket.getOutputStream(), BUFFSIZE);
        sendString("sometext");//This is working fine
    }

    public void sendString(String str) throws IOException
    {
        ByteArrayOutputStream bytestream;
        bytestream = new ByteArrayOutputStream(str.length());

        DataOutputStream out;
        out = new DataOutputStream(bytestream);

        for (int i = 0; i < str.length(); i++)
            out.write((byte) str.charAt(i));

        output.write(bytestream.toByteArray(), 0, bytestream.size());
        output.flush();
    }
}

另一个类.java

class AnotherClass
{
    public send()
    {
        Sample smp = new Sample();
        smp.sendString("somestring");//This is not working
    }
}

每当我在 AnotherClass.java 中调用 sendstring 方法时,它都会给我一个 NullPointerExcetpiton。我无法弄清楚。任何人都可以帮助我..提前谢谢....

4

2 回答 2

2

因为你还没有初始化

private BufferedOutputStream output;

所以当你调用

smp.sendString("somestring");//This is not working

output一片空白。您需要先执行方法public handleRequest(Socket socket){来初始化输出流

编辑

您可以重构您的方法并将初始化提取到另一种方法......但我不确定这是否是您正在寻找的......

public OutputStream initializeOutputStream(Socket socket, int size) {
     return new BufferedOutputStream(socket.getOutputStream(), size)
}

public handleRequest(Socket socket)
{
    this.output = initializeOutputStream(socket, BUFFSIZE);
    sendString("sometext");//This is working fine
}

然后在class AnotherClass只是使用而public OutputStream initializeOutputStream(Socket socket, int size)不是public handleRequest(Socket socket)

于 2012-11-27T13:40:05.763 回答
1

当您smp.sendString("something")在构造函数之后直接调用时,Sample smp=new Sample();您将在下一行中获得 NPE

output.write(bytestream.toByteArray(), 0, bytestream.size());

因为BufferedOutputStream output从未被初始化,因此是null

于 2012-11-27T13:39:11.613 回答