Read and write like java.nio

It's full of feelings now, but it's refreshing. I just want to get rid of the habit of writing directly to Stream.

For indefinite types

Channels.java


ReadableByteChannel inChannel = Channels.newChannel(InputStream);
WritableByteChannel outChannel = Channels.newChannel(OutputStream);

ByteBuffer buffer = ByteBuffer.allocate(102400);

for (int readBytes = inChannel.read(buffer); readBytes != -1; readBytes = inChannel.read(buffer)) {
    buffer.flip();
    outChannel.write(buffer);
    buffer.clear();
}

Reading and writing files 1

FileChannel1.java


File srcFile = new File(IN);
FileChannel in = new FileInputStream(srcFile).getChannel();
FileChannel out = new FileOutputStream(new File(OUT)).getChannel();

out.write(in.map(FileChannel.MapMode.READ_ONLY, 0, srcFile.length));

Reading and writing files 2

FileChannel2.java


FileChannel in = new FileInputStream(new File(IN)).getChannel();
FileChannel out = new FileOutputStream(new File(OUT)).getChannel();

in.transferTo(0, in.size(), out);

Recommended Posts

Read and write like java.nio
Sample to read and write LibreOffice Calc fods file in JRuby 2021
Sample to read and write LibreOffice Calc fods file in Java 2021
Let's introduce spock framework and write unit tests like test driven
Vuze plugin to write and enjoy
Read and generate QR code [Android]
Write keys and values in Ruby