好得很程序员自学网

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

Java复制文件常用的三种方法

复制文件 的三种方法:

1、files.copy(path, new fileoutputstream(dest));。

2、利用字节流。

3、利用字符流。

代码实现如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

package com.tiger.io;

import java.io.*;

import java.nio.file.*;

/**

  * 复制文件的三种方式

  * @author tiger

  * @date

  */

public class copyfile {

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

  path path = paths.get( "e:" , "17-06-15-am1.avi" );

  string dest = "e:\\copy电影.avi" ;

  copy01(path, dest);

  string src = "e:\\[java典型应用彻查1000例:java入门].pdf" ;

  string dest1 = "e:\\copyfile.pdf" ;

  copy02(src, dest1);

  //copy03(src, dest1);

  }

 

  /**

  * 利用files工具copy

  * @param path

  * @param dest

  * @throws ioexception

  * @throws ioexception

  */

  public static void copy01(path path,string dest) throws ioexception, ioexception{

  //利用files工具类对文件进行复制,简化编程,只需要写一句。

  files.copy(path, new fileoutputstream(dest));

  }

 

  /**

  * 利用字节流复制

  * @param src

  * @param dest

  * @throws ioexception

  */

  public static void copy02(string src,string dest) throws ioexception{

  inputstream is = new bufferedinputstream( new fileinputstream(src));

  outputstream os = new bufferedoutputstream( new fileoutputstream(dest));

  //文件拷贝u,-- 循环+读取+写出

  byte [] b = new byte [ 10 ]; //缓冲大小

  int len = 0 ; //接收长度

  //读取文件

  while (- 1 !=(len = is.read(b))) {

   //读入多少,写出多少,直到读完为止。

   os.write(b, 0 ,len);

  }

  //强制刷出数据

  os.flush();

  //关闭流,先开后关

  os.close();

  is.close();

  }

 

  /**

  * 字符流复制

  * @param src

  * @param dest

  * @throws ioexception

  */

  public static void copy03(string src,string dest) throws ioexception{

  //字符输入流

  bufferedreader reader = new bufferedreader( new filereader(src));

  //字符输出流

  bufferedwriter writer = new bufferedwriter( new filewriter(dest));

  char [] cbuf = new char [ 24 ];

  int len = 0 ;

  //边读入边写出

  while ((len = reader.read(cbuf)) != - 1 ) {

   writer.write(cbuf, 0 , len);

  }

  //关闭流

  writer.close();

  reader.close();

  }

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/qq_36336332/article/details/75950659

查看更多关于Java复制文件常用的三种方法的详细内容...

  阅读:17次