【IT168 技术文档】我把代码粘给大家,大家看测一下就知道下面两种方法种哪种方法的效率比较高:
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class IOTest { /** * @param args */ public static void main(String[] args) { long cc=System.currentTimeMillis(); for(int i=0;i<1000;i++){ test1(); } cc=System.currentTimeMillis()-cc; System.out.println("test1="+cc); cc=System.currentTimeMillis(); for(int i=0;i<1000;i++){ test2(); } cc=System.currentTimeMillis()-cc; System.out.println("test2="+cc); } private static void test1() { String file="test1.txt"; String message="asdfaksdjfalskdfjalksdjflkasjdfkajsdfkljasdlkfjasdlkfjasdfjalksdjflasdjflasdjflasdfjlasdfjeqoiuiruqnakncaskn asjdfas ffjqwoerj"; FileOutputStream fos=null; FileChannel fc=null; try { fos=new FileOutputStream(file,false); fc=fos.getChannel(); byte [] src=message.getBytes("GBK"); fc.write(ByteBuffer.wrap(src)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(null!=fos) fos.close(); } catch (IOException e) { e.printStackTrace(); } try { if(null!=fc) fc.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void test2() { String file="test2.txt"; String message="asdfaksdjfalskdfjalksdjflkasjdfkajsdfkljasdlkfjasdlkfjasdfjalksdjflasdjflasdjflasdfjlasdfjeqoiuiruqnakncaskn asjdfas ffjqwoerj"; FileOutputStream fos=null; try { fos=new FileOutputStream(file,false); byte [] src=message.getBytes("GBK"); fos.write(src); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(null!=fos) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }