「FileChannel」と「ByteBuffer」を使用してファイルをコピーするサンプルコードです。
java.nioパッケージの「FileChannel」と「ByteBuffer」を使用してファイルをコピーします。「ByteBuffer」のallocateDirect()を使用するとヒープ外のメモリ領域が割り当てられるため高速なアクセスが可能になります。しかし、割り当てのコストは高いため、容量の小さなデータを扱うには適していません。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioFileCopy {
public static void main(String[] args) {
System.out.println("--処理開始--");
if(args.length < 2)
{
System.out.println("コマンドライン引数を指定してください");
return;
}
FileChannel inChannel = null;
FileChannel outChannel = null;
try
{
FileInputStream in = new FileInputStream(args[0]);
inChannel = in.getChannel();
FileOutputStream out = new FileOutputStream(args[1]);
outChannel = out.getChannel();
ByteBuffer buff = ByteBuffer.allocateDirect(5120);
while(inChannel.read(buff) != -1)
{
buff.flip();
outChannel.write(buff);
buff.clear();
}
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
if(inChannel != null)
{
try
{
inChannel.close();
}catch(Exception e){ System.out.println(e); }
}
if(outChannel != null)
{
try
{
outChannel.close();
}catch(Exception e){ System.out.println(e); }
}
}
System.out.println("--処理終了--");
}
}
ちょっと一休み. Javaキーワード並び替えゲーム
画面に表示される文字列を並び替えるとJavaに関連するキーワードになります。ヒントをたよりに並び替えを行ってエンターを押してください。
ユーザ登録をしてログインするとランキングに参加できます。