Передача имени файла до передачи файла
Каким то чудом я смог в своем приложении реализовать перессылку файла на сервер, но теперь проблема в том, что имя файла захардкожено. Подскажите, пожалуйста, как сначала имя файла передать. То есть, чтобы сначала клиент передал имя файла, на сервере создался файл с таким именем и уже в него записывался byteBuffer. Код с клиента `
private static final String HOST = "localhost";
private static final int PORT = 9999;
public void sendFile(String path) throws IOException {
File file = new File(path);
System.out.println("file length = " + file.length());
FileChannel fileChannel = new FileInputStream(file).getChannel();
SocketAddress socketAddress = new InetSocketAddress(HOST, PORT);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(socketAddress);
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(file.length());
buffer.flip();
socketChannel.write(buffer);
long total = 0;
while (total < file.length()) {
long transferred = fileChannel.transferTo(total, file.length() - total, socketChannel);
total += transferred;
}
buffer.clear();
socketChannel.read(buffer);
buffer.flip();
long length = buffer.getLong();
System.out.println("bytes received by server = " + length);
socketChannel.finishConnect();
}
`
Код с сервера `
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
SocketChannel socketChannel = serverSocketChannel.accept();
final File outputFile = new File("rufus.exe");
ByteBuffer buffer = ByteBuffer.allocate(8);
socketChannel.read(buffer);
buffer.flip();
long length = buffer.getLong();
FileChannel fileChannel = new FileOutputStream(outputFile).getChannel();
long total = 0;
while (total < length) {
long transferred = fileChannel.transferFrom(socketChannel, total, length - total);
if (transferred <= 0){
break;
}
total += transferred;
}
buffer.clear();
buffer.putLong(total);
buffer.flip();
socketChannel.write(buffer);
serverSocketChannel.close();
System.out.println("length received = " + length + ", saved file length = " + outputFile.length());
}
`