Java NIO - Canal de fichier

La description

Comme déjà mentionné, l'implémentation FileChannel du canal Java NIO est introduite pour accéder aux propriétés des métadonnées du fichier, y compris la création, la modification, la taille, etc. Parallèlement à cela, les canaux de fichiers sont multithreads, ce qui rend à nouveau Java NIO plus efficace que Java IO.

En général, nous pouvons dire que FileChannel est un canal qui est connecté à un fichier par lequel vous pouvez lire des données d'un fichier et écrire des données dans un fichier.Une autre caractéristique importante de FileChannel est qu'il ne peut pas être mis en mode non bloquant et fonctionne toujours en mode de blocage.

Nous ne pouvons pas obtenir l'objet de canal de fichier directement, l'objet du canal de fichier est obtenu soit par -

  • getChannel() - méthode sur n'importe quel FileInputStream, FileOutputStream ou RandomAccessFile.

  • open() - méthode de canal de fichier qui par défaut ouvre le canal.

Le type d'objet du canal de fichier dépend du type de classe appelée depuis la création d'objet, c'est-à-dire que si l'objet est créé en appelant la méthode getchannel de FileInputStream, le canal de fichier est ouvert pour la lecture et lèvera NonWritableChannelException au cas où une tentative d'écrire dessus.

Exemple

L'exemple suivant montre comment lire et écrire des données à partir de Java NIO FileChannel.

L'exemple suivant lit un fichier texte à partir de C:/Test/temp.txt et imprime le contenu sur la console.

temp.txt

Hello World!

FileChannelDemo.java

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.Set;

public class FileChannelDemo {
   public static void main(String args[]) throws IOException {
      //append the content to existing file 
      writeFileChannel(ByteBuffer.wrap("Welcome to TutorialsPoint".getBytes()));
      //read the file
      readFileChannel();
   }
   public static void readFileChannel() throws IOException {
      RandomAccessFile randomAccessFile = new RandomAccessFile("C:/Test/temp.txt",
      "rw");
      FileChannel fileChannel = randomAccessFile.getChannel();
      ByteBuffer byteBuffer = ByteBuffer.allocate(512);
      Charset charset = Charset.forName("US-ASCII");
      while (fileChannel.read(byteBuffer) > 0) {
         byteBuffer.rewind();
         System.out.print(charset.decode(byteBuffer));
         byteBuffer.flip();
      }
      fileChannel.close();
      randomAccessFile.close();
   }
   public static void writeFileChannel(ByteBuffer byteBuffer)throws IOException {
      Set<StandardOpenOption> options = new HashSet<>();
      options.add(StandardOpenOption.CREATE);
      options.add(StandardOpenOption.APPEND);
      Path path = Paths.get("C:/Test/temp.txt");
      FileChannel fileChannel = FileChannel.open(path, options);
      fileChannel.write(byteBuffer);
      fileChannel.close();
   }
}

Production

Hello World! Welcome to TutorialsPoint