好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Java中IO字节流基本操作(复制文件)并测试性能

此次案例将以复制文件的形式来演示io字节流的基本操作,复制一个mp3文件,文件信息如下图:

main方法测试

?

1

2

3

4

5

6

7

8

9

10

11

12

public static void main(string[] args) throws exception {

        //源文件

        string srcfile = "src/a.mp3" ;

        //目的文件

        string destfile = "src/b.mp3" ;

        long start = system.currenttimemillis();

        ...

        复制文件方法

        ...

        long end = system.currenttimemillis();

        system.out.println( "共耗时" +(end-start)+ "毫秒" );

    }

一、一次读取一个字节

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

//一次读取一个字节

public static void copy1(string srcfile,string destfile) throws exception {

        

     //封装文件

     inputstream in = new fileinputstream(srcfile);

     outputstream out = new fileoutputstream(destfile);

        

     //复制文件

     int b = 0 ;

     while ((b = in.read()) != - 1 ) {

             out.write(b);

     }

        

     //释放资源

     in.close();

     out.close();

     }

运行截图:

二、一次读取一个字节数组

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// 一次读取一个字节数组

public static void copy2(string srcfile, string destfile) throws exception {

 

     // 封装文件

     inputstream in = new fileinputstream(srcfile);

     outputstream out = new fileoutputstream(destfile);

 

     // 复制文件

     byte [] buff = new byte [ 1024 ];

     int len = 0 ;

     while ((len = in.read(buff)) != - 1 ) {

             out.write(buff, 0 , len);

     }

 

     // 释放资源

     in.close();

     out.close();

     }

运行截图:

三、使用高效缓冲区一次读取一个字节

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/ 使用高效缓冲区一次读取一个字节

public static void copy3(string srcfile, string destfile) throws exception {

 

     // 封装文件

     bufferedinputstream bis = new bufferedinputstream( new fileinputstream(srcfile));

     bufferedoutputstream bos = new bufferedoutputstream( new fileoutputstream(destfile));

 

     // 复制文件

     int b = 0 ;

     while ((b = bis.read()) != - 1 ) {

             bos.write(b);

     }

 

     // 释放资源

     bis.close();

     bos.close();

     }

运行截图:

四、使用高效缓冲区一次读取一个字节数组

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// 使用高效缓冲区一次读取一个字节数组

public static void copy4(string srcfile, string destfile) throws exception {

 

     // 封装文件

     bufferedinputstream bis = new bufferedinputstream( new fileinputstream(srcfile));

     bufferedoutputstream bos = new bufferedoutputstream( new fileoutputstream(destfile));

 

     // 复制文件

     byte [] buf = new byte [ 1024 ];

     int len = 0 ;

     while ((len = bis.read(buf)) != - 1 ) {

             bos.write(buf, 0 , len);

     }

 

     // 释放资源

     bis.close();

     bos.close();

     }

运行截图:

注:每台测试的速度结果不一样

以上所述是小编给大家介绍的java中io字节流基本操作(复制文件)并测试性能,详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://blog.csdn.net/Y_Fei/article/details/89075903

查看更多关于详解Java中IO字节流基本操作(复制文件)并测试性能的详细内容...

  阅读:16次