Red de conocimiento informático - Conocimiento informático - Cómo leer y escribir archivos a través de FileChannel

Cómo leer y escribir archivos a través de FileChannel

importar java.io.File;

importar java.io.FileInputStream;

importar java.io.FileOutputStream;

importar java.io.IOException.

importar java.io.OutputStream;

importar java.nio.ByteBuffer;

importar java.nio.channels.FileChannel;

clase pública FileChannelDemo {

/**

* FileChannel es un canal para leer, escribir, mapear y operar archivos.

*

* Un FileChannel tiene una posición actual en su archivo que se puede consultar y modificar.

* El archivo en sí contiene una secuencia de bytes de longitud variable legible y escribible, y se puede consultar el tamaño actual del archivo.

* Cuando el número de bytes escritos excede el tamaño actual del archivo, el tamaño del archivo aumentará; cuando el archivo sea interceptado, el tamaño del archivo se reducirá.

Salida de archivo = new File("D:\\out.txt");

if(in.createNewFile()){

System.out .println("in.txt ha sido creado");

FileOutputStream es = new FileOutputStream(in);

byte[] b = "Podré hacerlo " .getBytes();

es.write(b, 0, b.length);

}

if(out.createNewFile()) {

System.out.println("out.txt ha sido creado");

}

FileInputStream es = new FileInputStream(in);

FileOutputStream os = new FileOutputStream(out);

FileChannel fis = is.getChannel();

FileChannel fos = os.getChannel();

ByteBuffer bytedata = ByteBuffer.allocate(100);

while(fis.read(bytedata)!= -1){

//Lectura/escritura intercalada por canal.

bytedata.flip();

fos.write(bytedata);

bytedata.clear();

}

fis.close();

fos.close();

os.close();

}

}

}