LoginSignup
1
0

More than 5 years have passed since last update.

java.nio的に読み書き

Posted at

今更感ありあふれますがさっくり。
ついStream直で書いちゃう癖なおしたいですね。

不定の型に対する場合

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();
}

ファイルの読み書き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));

ファイルの読み書き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);
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0