zoukankan      html  css  js  c++  java
  • 第四次作业

    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);
        }
    
    }
  • 相关阅读:
    js数字格式化(加千分位逗号)
    [css]解决iframe在ios设备上无法滚动
    判断当前是否在微信浏览器环境
    TortoiseGit 提交代码每次需要输入用户名和密码?
    如何编写jQuery插件
    函数作用域
    HTTP动词
    如何减少全局变量污染?
    mysql表大字段最大长度限制设置
    update left join 多表关联更新
  • 原文地址:https://www.cnblogs.com/zyw80/p/5388796.html
Copyright © 2011-2022 走看看