復制文件的三種方法:
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