gpt4 book ai didi

java - 从 java 服务器向 c++ 客户端发送数据时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 00:07:13 24 4
gpt4 key购买 nike

示例.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。我无法弄清楚。有人可以帮助我吗..先谢谢了......

最佳答案

因为你还没有初始化

private BufferedOutputStream output;

所以当你调用

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

输出为空。您需要执行方法 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 OutputStreaminitializeOutputStream(Socket socket, int size)而不是public handleRequest(Socket socket)

关于java - 从 java 服务器向 c++ 客户端发送数据时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585394/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com