用java實現ftp文件上傳。我使用的是commons-net-1.4.1.zip。其中包含了眾多的java網絡編程的工具包。
1.把commons-net-1.4.1.jar包加載到項目工程中去。
2.看如下代碼:
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
|
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FileTool { /** * Description: 向FTP服務器上傳文件 * @Version 1.0 * @param url FTP服務器hostname * @param port FTP服務器端口 * @param username FTP登錄賬號 * @param password FTP登錄密碼 * @param path FTP服務器保存目錄 * @param filename 上傳到FTP服務器上的文件名 * @param input 輸入流 * @return 成功返回true,否則返回false * */ public static boolean uploadFile(String url, // FTP服務器hostname int port, // FTP服務器端口 String username, // FTP登錄賬號 String password, // FTP登錄密碼 String path, // FTP服務器保存目錄 String filename, // 上傳到FTP服務器上的文件名 InputStream input // 輸入流 ){ boolean success = false ; FTPClient ftp = new FTPClient(); ftp.setControlEncoding( "GBK" ); try { int reply; ftp.connect(url, port); // 連接FTP服務器 // 如果采用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器 ftp.login(username, password); // 登錄 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.makeDirectory(path); ftp.changeWorkingDirectory(path); ftp.storeFile(filename, input); input.close(); ftp.logout(); success = true ; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } return success; } /** * 將本地文件上傳到FTP服務器上 * */ public static void upLoadFromProduction(String url, // FTP服務器hostname int port, // FTP服務器端口 String username, // FTP登錄賬號 String password, // FTP登錄密碼 String path, // FTP服務器保存目錄 String filename, // 上傳到FTP服務器上的文件名 String orginfilename // 輸入流文件名 ) { try { FileInputStream in = new FileInputStream( new File(orginfilename)); boolean flag = uploadFile(url, port, username, password, path,filename, in); System.out.println(flag); } catch (Exception e) { e.printStackTrace(); } } //測試 public static void main(String[] args) { upLoadFromProduction( "192.168.13.32" , 21 , "hanshibo" , "han" , "韓士波測試" , "hanshibo.doc" , "E:/temp/H2數據庫使用.doc" ); } } |
3.直接運行。即可把指定的文件上傳到ftp服務器.有需要jar包的可以到我的資源中去下載。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/atomcrazy/article/details/8943194