我正在尝试使用套接字发送文件,但是当我收到文件时,无法存储它。
调试器显示,代码停止在
bytesRead =
is.read(mybytearray,current,(mybytearray.length-current));
并没有任何反应。
bytesRead = is.read(mybytearray,0,mybytearray.length);
-等于17
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
Socket socket = null;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
socket = serverSocket.accept();
System.out.println("Accepted connection : " + socket);
int bytesRead;
int current = 0;
byte[] mybytearray = new byte[FILE_SIZE];
InputStream is = socket.getInputStream();
fileOutputStream = new FileOutputStream(FILE_TO_RECEIVED);
bufferedOutputStream = new BufferedOutputStream(bufferedOutputStream);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length - current));
if (bytesRead >= 0) current += bytesRead;
} while (bytesRead > -1);
bufferedOutputStream.write(mybytearray, 0, current);
bufferedOutputStream.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " recieved (" + current + " bytes read)");
} finally {
if (fileOutputStream != null) fileOutputStream.close();
if (bufferedOutputStream != null) bufferedOutputStream.close();
if (socket != null) socket.close();
}
}
} finally {
if (serverSocket != null) serverSocket.close();
}
}
最佳答案
您可以尝试直接写入OutputStream,例如将您的while循环更改为
while ((bytesRead = in.read(mybytearray)) > 0) {
fileOutputStream.write(mybytearray, 0, bytesRead);
}
根据菜鸟答案的描述-
https://stackoverflow.com/a/9548429/2826895