「FileChannel」と「ByteBuffer」を使用してファイルをメモリにマップし、ファイルをコピーするサンプルコードです。
java.nioパッケージの「FileChannel」と「ByteBuffer」を使用してファイルをコピーします。メモリマッピングはダイレクトバッファを使用するため、高速にデータにアクセスできますが、マッピング処理自体は負荷が高い処理ですので、小さなサイズのデータを扱うの場合は、パフォーマンスに対する効果がありません。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MapFileCopy {
public static void main(String[] args) {
System.out.println("--処理開始--");
if(args.length < 2)
{
System.out.println("コマンドライン引数を指定してください");
return;
}
FileChannel inChannel = null;
FileChannel outChannel = null;
try
{
int MAP_SIZE = 1048576;
FileInputStream in = new FileInputStream(args[0]);
inChannel = in.getChannel();
FileOutputStream out = new FileOutputStream(args[1]);
outChannel = out.getChannel();
long fileSize = inChannel.size();
int position = 0;
while( position < fileSize)
{
int length = 0;
if(position + MAP_SIZE < fileSize)
{
length = MAP_SIZE;
}
else
{
length = (int)(fileSize - position);
}
ByteBuffer buff
= inChannel.map(FileChannel.MapMode.READ_ONLY, position, length);
outChannel.write(buff);
position += length;
}
}
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に関連するキーワードになります。ヒントをたよりに並び替えを行ってエンターを押してください。
ユーザ登録をしてログインするとランキングに参加できます。