Please see code below:
s = new Socket(nextHopIP, 3434);
fileIn = new FileInputStream(fileName);
fileOut = s.getOutputStream();
buffer = new byte[bufferSize];
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw.println(fromIP);
pw.println(toIP);
pw.println(fileName.split("\\\\")[fileName.split("\\\\").length - 1]);
pw.flush();
//Send file
fileTransferTime = System.currentTimeMillis();
while((readFile = fileIn.read(buffer)) != -1) {
fileOut.write(buffer, 0, readFile);
}
pw.println("");
pw.flush();
fileIn.close();
fileOut.close();
br.readLine(); //error here
fileTransferTime = System.currentTimeMillis() - fileTransferTime;
System.out.println("File transfer time: " + fileTransferTime);
pw.close();
br.close();
s.close();
By the time it reaches br.readLine(), socket closed exception is raised. I’ve only closed the outputstream so far. Does closing the outputstream also closes the inputstream in this case?
Thanks!
From the API docs of
java.net.Socket.getOutputStreambris closed because it decorates the input stream associated with the socket. Strange, but true. It is possible to half-close a socket.Also note that resource handling should be done as:
(Possibly using the Execute Around idiom.)