15 Haziran 2023 Perşembe

FileChannel.transferTo metodu - Zero Copy

Giriş
Source Channel nesnesinden, Destination Channel nesnesine kopyalama yapar. 

Zero Copy Nedir?
 Açıklaması şöyle
Zero Copy is a technique employed in computer systems to minimize data copying and movement during data transfer operations. It aims to improve performance and reduce resource utilization by avoiding unnecessary data copying.
Zero Copy Nasıl Yapılır?
 Açıklaması şöyle
The Java class libraries support zero copy on Linux and UNIX systems through the transferTo() method in java.nio.channels.FileChannel. You can use the transferTo() method to transfer bytes directly from the channel on which it is invoked to another writable byte channel, without requiring data to flow through the application.
Örnek - Dosyadan Dosyaya Kopyalama
FileChannel nesnesinden FileChannel nesnesine kopyalanır
Örnek
Şöyle yaparız.
void fileCopyUsingNIOChannelClass() throws IOException {
  File fileToCopy = new File("c:/temp/testoriginal.txt");
  FileInputStream inputStream = new FileInputStream(fileToCopy);
  FileChannel inChannel = inputStream.getChannel();

  File newFile = new File("c:/temp/testcopied.txt");
  FileOutputStream outputStream = new FileOutputStream(newFile);
  FileChannel outChannel = outputStream.getChannel();

  inChannel.transferTo(0, fileToCopy.length(), outChannel);

  inputStream.close();
  outputStream.close();
}
Örnek - Dosyadan Sockete Kopyalama
FileChannel nesnesinden SocketChannel nesnesine kopyalanır. Şöyle yaparız. İstemci bir sunucuya dosya gönderiyor
String host = "localhost";
int port = 9026;
SocketAddress socketAddress = new InetSocketAddress(host, port);
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(socketAddress);
socketChannel.configureBlocking(true);
String fname = ...; long fsize = 183678375L; FileChannel fileChannel = new FileInputStream(fname).getChannel(); long sentBytes = fileChannel.transferTo(0, fsize, socketChannel);
fileChannel.close();


Hiç yorum yok:

Yorum Gönder