In the Java program, often need to deal with FTP, such as uploading files to the FTP server, download files, this article briefly describes how to use the FtpClient in the Jakarta Commons (in the Commons-net package) to achieve upload download files.
The jar packages used are:
Commons-net-1.4.1.jar
Jakarta-oro.jar
First, upload files to view the source print?
01 |
File Upload source code |
03 |
* Description: Uploading files to FTP server |
05 |
* @param URL FTP server hostname |
06 |
* @param port FTP server ports |
07 |
* @param username FTP login Account |
08 |
* @param password FTP login password |
09 |
* @param path FTP server save directory |
10 |
* @param filename uploaded to the FTP server |
12 |
* @return Returns True successfully, otherwise returns false |
14 |
public static Boolean UploadFile ( |
15 |
String URL,//FTP Server hostname |
16 |
int PORT,//FTP Server Port |
17 |
String username,//FTP login account |
18 |
String password,//ftp login password |
19 |
String path,//ftp server save directory |
20 |
String filename,//Upload file name on FTP server |
21st |
InputStream input//input stream |
23 |
Boolean success = false; |
24 |
ftpclient ftp = new FtpClient (); |
27 |
Ftp.connect (URL, port);//Connect FTP server |
28 |
If you use the default port, you can connect to the FTP server directly using the Ftp.connect (URL) method |
29 |
Ftp.login (username, password);/Login |
30 |
Reply = Ftp.getreplycode (); |
31 |
if (! Ftpreply.ispositivecompletion (Reply)) { |
35 |
Ftp.changeworkingdirectory (path); |
36 |
Ftp.storefile (filename, input); |
41 |
catch (IOException e) { |
44 |
if (ftp.isconnected ()) { |
47 |
catch (IOException IoE) { |
The following is a file upload test case: Check the source print?
02 |
* Upload the local file to the FTP server |
05 |
public void Testuploadfromdisk () { |
07 |
FileInputStream in=new FileInputStream (New File ("D:/test.txt")); |
08 |
Boolean flag = UploadFile ("127.0.0.1", "Administrator", "zyuc2011", "Test", "test.txt", in); |
09 |
SYSTEM.OUT.PRINTLN (flag); |
10 |
catch (FileNotFoundException e) { |
View the source print?
02 |
* Generate a file on the FTP server and write a string to the file |
05 |
public void testuploadfromstring () { |
07 |
String str = "This is the string to write." "; |
08 |
InputStream input = new Bytearrayinputstream (str.getbytes ("Utf-8")); |
09 |
Boolean flag = UploadFile ("127.0.0.1", "Administrator", "zyuc2011", "Test", "test.txt", input); |
10 |
SYSTEM.OUT.PRINTLN (flag); |
11 |
catch (Unsupportedencodingexception e) { |
Second, File download view source printing?
01 |
File Download Source code |
03 |
* Description: Downloading files from FTP server |