- バッファーを利用してファイルをコピーするアプリケーション"NewIO01.java"を作成し、実行してください。コピー元ファイル名、コピー先ファイル名は、コマンドラインから指定します。
- import java.io.*;
- import java.nio.*;
- import java.nio.channels.*;
-
- public class NewIO01 {
- public static void main(String[] args) {
- File f = null;
- ByteBuffer bb = null;
- FileChannel fci = null;
- FileChannel fco = null;
-
- try {
- f = new File(args[0]);
- fci = new FileInputStream(f).getChannel();
- fco = new FileOutputStream(args[1]).getChannel();
-
- bb = ByteBuffer.allocate((int)f.length()); // 入力ファイルの大きさ分のバッファの割り当て
- printProperty(bb, "割当て後");
-
- fci.read(bb); // 入力
- printProperty(bb, "入力後");
-
- bb.flip(); // フリップ
- printProperty(bb, "フリップ後");
-
- fco.write(bb); // 出力
- printProperty(bb, "出力後");
-
- fco.close();
- fci.close();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void printProperty(ByteBuffer bb, String msg) {
- System.out.println("* " + msg);
- System.out.print(" position = " + bb.position());
- System.out.print(" limit = " + bb.limit());
- System.out.print(" capacity = " + bb.capacity());
- System.out.println();
- }
- }
□ 実行結果
$ java NewIO01 NewIO01.java NewIO01.java.txt
* 割当て後
position = 0 limit = 1406 capacity = 1406
* 入力後
position = 1406 limit = 1406 capacity = 1406
* フリップ後
position = 0 limit = 1406 capacity = 1406
* 出力後
position = 1406 limit = 1406 capacity = 1406