廢話不多說了,直接給大家貼代碼了,具體代碼如下所示:
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
//文件上傳 public static boolean uploadToFTP(String url, int port,String username,String password,String path,String filename,InputStream input) { boolean success= false ; try { if (port>- 1 ) { ftp.connect(url,port); } else { ftp.connect(url); //ftp默認的端口是21 } //很多人寫的是用ftp.getReplyCode()給獲取連接的返回值,但是這樣會導致storeFileStream返回null if (ftp.login(username,password)) { ftp.enterLocalActiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); //創建目錄,如果存在會返回失敗 ftp.makeDirectory(path); //切換目錄 ftp.changeWorkingDirectory(path); //上傳文件 //FTP協議規定文件編碼格式為ISO-8859-1 filename= new String(filename.getBytes( "GBK" ), "ISO-8859-1" ); OutputStream out=ftp.storeFileStream(filename); byte []byteArray= new byte [ 4096 ]; int read= 0 ; while ((read=input.read(byteArray))!=- 1 ) { out.write(byteArray, 0 ,read); } out.close(); ftp.logout(); sucess= true ; } } catch (Exception e) { } finally { if (ftp.isConnected()) { ftp.disConnecct(); } } } //文件下載 public static boolean downloadFromFTP(String url, int port,String username,String password,String path,String localpath) { boolean success= false ; FTPClient ftp= new FTPClient(); //org.apache.commons.net.ftp try { int reply; if (port>- 1 ) { ftp.connect(url,port); } else { ftp.connect(url); //ftp默認的端口是21 } //很多人寫的是用ftp.getReplyCode()給獲取連接的返回值,但是這樣會導致storeFileStream返回null ftp.login(username,password) ftp.enterLocalActiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); reply=ftp.getReplyCode(); if (!FTPReply.isPositionCompletion(reply)) { ftp.disconnect(); return success;s } //切換目錄 此處可以判斷,切換失敗就說明ftp上面沒有這個路徑 ftp.changeWorkingDirectory(path); //上傳文件 FTPFile[]fs=ftp.listFiles(); OutputStream out= null ; InputStream in= null ; for ( int i= 0 ;i<fs.length;i++) { FTPFile ff=fs[i]; String outFileName=ff.getName(); //創建本地的文件時候要把編碼格式轉回來 String localFileName= new String(ff.getName().getBytes( "ISO-8859-" ), "GBK" ); File localFile= new File(localpath+lcoalFileName); out= new FileOutputStream(localFile); in=ftp.retrieveFileStream(outFileName); byte []byteArray= new byte [ 4096 ]; int read= 0 ; while ((read=in.read(byteArray))!=- 1 ) { out.write(byteArray, 0 ,read); } //這句很重要 要多次操作這個ftp的流的通道,要等他的每次命令完成 ftp.completePendingCommand(); out.flush(); out.close(); ftp.logout(); sucess= true ; } catch (Exception e) { } finally { if (ftp.isConnected()) { ftp.disConnecct(); } } } |
以上所述是小編給大家介紹的Java實現ftp文件上傳下載解決慢中文亂碼多個文件下載等問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!