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);
        }
    
    }
  • 相关阅读:
    【python】python中的定义类属性和对像属性
    【Python】Python—判断变量的基本类型
    【python】Python中给List添加元素的4种方法分享
    【python】python各种类型转换-int,str,char,float,ord,hex,oct等
    【python】python 中的三元表达式(三目运算符)
    【python】 sort、sorted高级排序技巧
    【SQLAlchemy】SQLAlchemy技术文档(中文版)(中)
    【SQLAlchemy】SQLAlchemy技术文档(中文版)(上)
    【其他】VS提示不一致的行尾
    UML 之 用例图
  • 原文地址:https://www.cnblogs.com/zyw80/p/5388796.html
Copyright © 2011-2022 走看看