トップ 差分 一覧 ソース 置換 検索 ヘルプ PDF RSS ログイン

NIOでファイル操作

http://www.techscore.com/tech/J2SE/NIO/index.html
http://www.javainthebox.net/laboratory/JDK1.4/contents.html

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class test {
  public static void main(String[] args){
    new test();
  }
  
  public test(){
    copyFileByStream("data.dat", "data_stream.dat");
    copyFileByChannel("data.dat", "data_channels.dat");
  }
  
  public void copyFileByChannel(String srcFilename, String destFilename){
    try{
      FileChannel in = (new FileInputStream(srcFilename)).getChannel();
      FileChannel out = (new FileOutputStream(destFilename)).getChannel();
      
      long start = System.currentTimeMillis();
      
      ByteBuffer buffer = ByteBuffer.allocateDirect(10000000);
      
      while (true) {
        buffer.clear();
        if(in.read(buffer) < 0){
          break;
        }
        buffer.flip();
        out.write(buffer);
      }
      
      long end = System.currentTimeMillis();
      
      System.out.println("Total time = " + (end-start));
      
      out.close();
      in.close();
    }catch(FileNotFoundException ex){
      ex.printStackTrace();
    }catch(IOException ex){
      ex.printStackTrace();
    }
  }
  public void copyFileByStream(String srcFilename, String destFilename){
    try{
      // InputStream in = new FileInputStream(srcFilename);
      // OutputStream out = new FileOutputStream(destFilename);
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFilename));
      BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFilename));
      
      long start = System.currentTimeMillis();
      
      byte[] buffer = new byte[10000000];
      int n;
      while ((n = in.read(buffer)) != -1) {
        out.write(buffer, 0, n);
      }
      
      out.flush();
      
      long end = System.currentTimeMillis();
      
      System.out.println("Total time = " + (end-start));
      out.close();
      in.close();
    }catch(FileNotFoundException ex){
      ex.printStackTrace();
    }catch(IOException ex){
      ex.printStackTrace();
    }
  }
}

[カテゴリ: プログラミング言語 > Java]

[通知用URL]



  • Hatenaブックマークに追加
  • livedoorクリップに追加
  • del.icio.usに追加
  • FC2ブックマークに追加

最終更新時間:2008年05月25日 22時04分49秒