Answer the question
In order to leave comments, you need to log in
What is the correct way to transfer a file through Java NIO?
//Цикл принимающей стороны
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(
Paths.get(file.getPath()), StandardOpenOption.WRITE);
while (true) {
if (offset == fileSize) {
//конец
}
byte[] response = receiveByteArray();
int bytesRead = offset + response.length >= fileSize ? (int) (fileSize - offset) : response.length;
fileChannel.write(ByteBuffer.wrap(Arrays.copyOfRange(response, 0, bytesRead)), offset);
offset += bytesRead;
System.out.println(server.socket().getRemoteSocketAddress() + " >>> " + bytesRead + " bytes");
}
private byte[] receiveByteArray() throws IOException {
ByteBuffer readBuffer = ByteBuffer.allocate(Constants.BUFFER_SIZE); //size = 1460
server.read(readBuffer); //label 1
readBuffer.flip();
return readBuffer.array();
}
//Отправление массива байт
private void send(SelectionKey key, byte[] response) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
client.write(ByteBuffer.wrap(response));
client.socket().getOutputStream().flush();
System.out.println(client.socket().getRemoteSocketAddress().toString() + " <<< " + response.length + " bytes");
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question