Java implementation of FTP file upload and download function of the instance code

  • 2020-05-17 05:38:08
  • OfStack

FTP is short for File Transfer Protocol (file transfer protocol) in English, but short for "text transfer protocol" in Chinese. For two-way transfer of control files on Internet. It is also an application (Application). There are different FTP applications based on different operating systems, and all of these applications adhere to the same protocol to transfer files. In the use of FTP, users often encounter two concepts: "download" (Download) and "upload" (Upload). To download "a file is to copy a file from a remote host to your own computer." To upload a file is to copy it from your own computer to a remote host. In Internet, users can upload (download) files to (from) a remote host via a client program.

First of all, I downloaded Serv-U and set up my computer as FTP file server for easy operation.

1. Download of FTP files (from the FTP server to the machine)


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FtpApche {
private static FTPClient ftpClient = new FTPClient();
private static String encoding = System.getProperty("file.encoding");
/**
* Description:  from FTP Server download file 
* 
* @Version1.0
* @param url
* FTP The server hostname
* @param port
* FTP Server port 
* @param username
* FTP Login account 
* @param password
* FTP The login password 
* @param remotePath
* FTP The relative path on the server 
* @param fileName
*  The file name to download 
* @param localPath
*  Save to the local path after downloading 
* @return
*/
public static boolean downFile(String url, int port, String username,
String password, String remotePath, String fileName,
String localPath) {
boolean result = false;
try {
int reply;
ftpClient.setControlEncoding(encoding);
/*
*  In order to upload and download Chinese files, some places suggest using the following two sentences instead 
* new String(remotePath.getBytes(encoding),"iso-8859-1") Transcoding. 
*  After testing, it didn't pass. 
*/
// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
// conf.setServerLanguageCode("zh");
ftpClient.connect(url, port);
//  If the default port is used, it can be used ftp.connect(url) The way of direct connection FTP The server 
ftpClient.login(username, password);//  The login 
//  Set the file transfer type to 2 Into the system 
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//  To obtain ftp Login reply code 
reply = ftpClient.getReplyCode();
//  Verify that the login was successful 
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
return result;
}
//  Transferred to the FTP Server directory to the specified directory 
ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1"));
//  Get a list of files 
FTPFile[] fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(ff.getName(), is);
is.close();
}
}
ftpClient.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
/**
*  will FTP The file on the server is downloaded locally 
* 
*/
public void testDownFile() {
try {
boolean flag = downFile("10.0.0.102", 21, "admin",
"123456", "/", "ip.txt", "E:/");
System.out.println(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FtpApche fa = new FtpApche();
fa.testDownFile();
}
}

2. Upload of FTP files (from the local machine to FTP server)


import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FTPTest_05 {
private FTPClient ftp;
/** 
* 
* @param path  Uploaded to the ftp Which path is under the server  
* @param addr  address  
* @param port  The port number  
* @param username  The user name  
* @param password  password  
* @return 
* @throws Exception 
*/ 
private boolean connect(String path,String addr,int port,String username,String password) throws Exception {
boolean result = false;
ftp = new FTPClient();
int reply;
ftp.connect(addr,port);
ftp.login(username,password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(path);
result = true;
return result;
}
/** 
* 
* @param file  An uploaded file or folder  
* @throws Exception 
*/ 
private void upload(File file) throws Exception{
if(file.isDirectory()){
ftp.makeDirectory(file.getName());
ftp.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (int i = 0;i < files.length;i++) {
File file1 = new File(file.getPath()+"\\"+files[i] );
if(file1.isDirectory()){
upload(file1);
ftp.changeToParentDirectory();
}else{
File file2 = new File(file.getPath()+"\\"+files[i]);
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
}else{
File file2 = new File(file.getPath());
FileInputStream input = new FileInputStream(file2);
ftp.storeFile(file2.getName(), input);
input.close();
}
}
public static void main(String[] args) throws Exception{
FTPTest_05 t = new FTPTest_05();
boolean connFlag = t.connect("/", "10.0.0.105", 21, "ls", "123456");
System.out.println("connFlag : " + connFlag);
File file = new File("D:\\test02");// The address of the local file to be transmitted 
System.out.println("file : " + file);
t.upload(file);
System.out.println("upload : " + "ok");
}
}

Related articles: