我请求帮助 在客户端接收文件。变量输入记录文件名。Inputstream "is" 和 FileOutputStream "bos" 负责保存文件。第一个文件已交付,但另一个收到的文件在变量名称中发生 java.lang.NullPointerException。如何处理此循环以创建文件,输入变量将包含文件的下一个新名称,流“is”将包含新数据?文件toxic.pill 表示传输结束。
public class Receiver implements Runnable {
private int port;
public Receiver(int port) {
this.port = port;
}
@Override
public void run() {
Socket socket = null;
BufferedOutputStream bos = null;
try {
InetAddress adresa = InetAddress.getByName("localhost");
System.out.println("klient sa pripaja na adresu: " + adresa);
socket = new Socket(adresa, this.port);
System.out.println("socket = " + socket);
while (true) {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String name = input.readLine();
/// while (???????) {}
if (name.equals("poison.pill")) {// null pointer exception
bos.close();
socket.close();
break;
}
int filesize = 1400;
int bytesRead;
byte[] bytearray = new byte[filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(name);
bos = new BufferedOutputStream(fos);
while ((bytesRead = is.read(bytearray)) != -1) {
bos.write(bytearray, 0, bytesRead);
bos.flush();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
万一有误会我解释一下。