• 第四次作业


    import java.io.FileInputStream;

    import java.io.FileOutputStream;

    import java.io.IOException;

    public class CopyFile {

           /**

            * @param args

            */

           public static void main(String[] args) {

                  try {

                         FileInputStream fis = new FileInputStream ("a.jpg");

                         FileOutputStream fos = new FileOutputStream ("temp.jpg");

                         int read = fis.read();            

                         while ( read != -1 ) {

                                fos.write(read);     

                                read = fis.read();

                         }                  

                         fis.close();

                         fos.close();

                  } catch (IOException e) {

                         e.printStackTrace();

                  }

           }

    }

    但是,这段代码在复制如mp3等大文件时,运行效率很低,即运行时间长。

    下面是改进的代码

    复制代码
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.channels.FileChannel;
    
    
    public class fileChannelCopy {
    
        /**
         * @param args
         */
        public static void fileChannelCopy(File a ,File b){
            FileInputStream fi = null;
            FileOutputStream fo = null;
            FileChannel in = null;
            FileChannel out = null;
            
            try {
                fi = new FileInputStream(a);
                fo = new FileOutputStream(b);
                in = fi.getChannel();
                out = fo.getChannel();
                try {
                    in.transferTo(0, in.size(), out);
                     fi.close();
    
                        in.close();
    
                        fo.close();
    
                        out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        }
          
        public static void main(String[] args) {
            // TODO Auto-generated method stub
         File a = new File("a.mp3");
         File b = new File("temp.jpg");
         fileChannelCopy(a,b);
        }
    
    }
  • 相关阅读:
    poj3068
    tyvj1864 [Poetize I]守卫者的挑战
    BZOJ1597 [Usaco2008 Mar]土地购买
    [AtCoder Regular Contest 083] Bichrome Tree
    [LUOGU]3919 【模板】可持久化数组
    [LUOGU]P3701 主席树(假的)
    2018.7.20模拟赛
    [CodeForces]1006F Xor Path
    2018.7.19模拟赛
    [LUOGU]P1373 小a和uim之大逃离
  • 原文地址:https://www.cnblogs.com/zyw80/p/5388796.html
Copyright © 2020-2023  润新知