java implements FTP file upload and file download

  • 2020-05-09 18:34:11
  • OfStack

In this paper, we share two ways to upload and download FTP files by java for your reference. The details are as follows

Method 1:


package com.cloudpower.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
 * Java built-in API right FTP The operation of the 
 * @Title:Ftp.java
 * @author:  Zhou Lingbin  
 */
public class Ftp {
 /**
 *  Local file name 
 */
 private String localfilename;
 /**
 *  Remote file name 
 */
 private String remotefilename;
 /**
 * FTP The client 
 */
 private FtpClient ftpClient;

 /**
 *  Server connection 
 * @param ip  The server IP
 * @param port  Server port 
 * @param user  The user name 
 * @param password  password 
 * @param path  Server path 
 * @author  Zhou Lingbin 
 * @date 2012-7-11
 */
 public void connectServer(String ip, int port, String user,
 String password, String path) {
 try {
 /* ****** Two ways to connect to a server *******/
 // The first 1 methods 
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
 // The first 2 methods 
 ftpClient = new FtpClient(ip);
 
 ftpClient.login(user, password);
 //  Set to 2 Hexadecimal transmission 
 ftpClient.binary();
 System.out.println("login success!");
 if (path.length() != 0){
 // Switch directories on the remote system to parameters path The specified directory 
 ftpClient.cd(path);
 }
 ftpClient.binary();
 } catch (IOException ex) {
 ex.printStackTrace();
 throw new RuntimeException(ex);
 }
 }
 /**
 *  Close the connection 
 * @author  Zhou Lingbin 
 * @date 2012-7-11
 */
 public void closeConnect() {
 try {
 ftpClient.closeServer();
 System.out.println("disconnect success");
 } catch (IOException ex) {
 System.out.println("not disconnect");
 ex.printStackTrace();
 throw new RuntimeException(ex);
 }
 }
 /**
 *  Upload a file 
 * @param localFile  The local file 
 * @param remoteFile  The remote file 
 * @author  Zhou Lingbin 
 * @date 2012-7-11
 */
 public void upload(String localFile, String remoteFile) {
 this.localfilename = localFile;
 this.remotefilename = remoteFile;
 TelnetOutputStream os = null;
 FileInputStream is = null;
 try {
 // Adds the remote file to the output stream 
 os = ftpClient.put(this.remotefilename);
 // Gets the input stream for the local file 
 File file_in = new File(this.localfilename);
 is = new FileInputStream(file_in);
 // create 1 A buffer 
 byte[] bytes = new byte[1024];
 int c;
 while ((c = is.read(bytes)) != -1) {
 os.write(bytes, 0, c);
 }
 System.out.println("upload success");
 } catch (IOException ex) {
 System.out.println("not upload");
 ex.printStackTrace();
 throw new RuntimeException(ex);
 } finally{
 try {
 if(is != null){
  is.close();
 }
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 try {
  if(os != null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
 }
 }
 
 /**
 *  The download file 
 * @param remoteFile  Remote file path ( The server side )
 * @param localFile  Local file path ( The client )
 * @author  Zhou Lingbin 
 * @date 2012-7-11
 */
 public void download(String remoteFile, String localFile) {
 TelnetInputStream is = null;
 FileOutputStream os = null;
 try {
 // Gets the files on the remote machine filename , with the aid of TelnetInputStream Transfer the file locally. 
 is = ftpClient.get(remoteFile);
 File file_in = new File(localFile);
 os = new FileOutputStream(file_in);
 byte[] bytes = new byte[1024];
 int c;
 while ((c = is.read(bytes)) != -1) {
 os.write(bytes, 0, c);
 }
 System.out.println("download success");
 } catch (IOException ex) {
 System.out.println("not download");
 ex.printStackTrace();
 throw new RuntimeException(ex);
 } finally{
 try {
 if(is != null){
  is.close();
 }
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 try {
  if(os != null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 }
 }
 }

 public static void main(String agrs[]) {

 String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
 String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

 Ftp fu = new Ftp();
 /*
 *  Use the default port number, username, password, and root connection FTP The server 
 */
 fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");
 
 // download 
 for (int i = 0; i < filepath.length; i++) {
 fu.download(filepath[i], localfilepath[i]);
 }
 
 String localfile = "E:\\ number .txt";
 String remotefile = "/temp/ Ha ha .txt";
 // upload 
 fu.upload(localfile, remotefile);
 fu.closeConnect();
 }
}

This way has nothing to say, is relatively simple, also does not exist the Chinese garbled code problem. Seems to have a defect, can not operate the large file, interested friends can try.

The second way:


public class FtpApche {
 private static FTPClient ftpClient = new FTPClient();
 private static String encoding = System.getProperty("file.encoding");
 /**
 * Description:  to FTP Server upload 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 path
 * FTP Server save directory , If it's the root directory, it's" / " 
 * @param filename
 *  Uploaded to the FTP The file name on the server 
 * @param input
 *  Local file input stream 
 * @return  Successfully returns true Otherwise return false
 */
 public static boolean uploadFile(String url, int port, String username,
 String password, String path, String filename, InputStream input) {
 boolean result = false;

 try {
 int reply;
 //  If the default port is used, it can be used ftp.connect(url) The way of direct connection FTP The server 
 ftpClient.connect(url);
 // ftp.connect(url, port);//  The connection FTP The server 
 //  The login 
 ftpClient.login(username, password);
 ftpClient.setControlEncoding(encoding);
 //  Verify that the connection was successful 
 reply = ftpClient.getReplyCode();
 if (!FTPReply.isPositiveCompletion(reply)) {
 System.out.println(" The connection fails ");
 ftpClient.disconnect();
 return result;
 }

 //  Transfer the working directory to the specified directory 
 boolean change = ftpClient.changeWorkingDirectory(path);
 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
 if (change) {
 result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"), input);
 if (result) {
  System.out.println(" Uploaded successfully !");
 }
 }
 input.close();
 ftpClient.logout();
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 if (ftpClient.isConnected()) {
 try {
  ftpClient.disconnect();
 } catch (IOException ioe) {
 }
 }
 }
 return result;
 }

 /**
 *  Upload the local file to FTP On the server 
 * 
 */
 public void testUpLoadFromDisk() {
 try {
 FileInputStream in = new FileInputStream(new File("E:/ number .txt"));
 boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", " Ha ha .txt", in);
 System.out.println(flag);
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 }
 }


 /**
 * 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("127.0.0.1", 21, "zlb",
  "123", "/", " Ha ha .txt", "D:/");
 System.out.println(flag);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 
 public static void main(String[] args) {
 FtpApche fa = new FtpApche();
 fa.testDownFile();
 }
}

This way of words need to pay attention to the Chinese garble code problem, if you do not set the appropriate, it is possible to upload the file name will be garble code, sometimes can not upload up, of course, will not tell you, because there is no exception. On the Internet to find a lot of solutions, opinions vary, almost all from a version of the copy of the past, also did not pass their own true test. For this, also suffered a lot. There are basically two solutions:

1. Add the following three sentences to solve the problem

ftpClient. setControlEncoding (" GBK ");

FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");

Answer: after testing, it basically didn't work, and the above problem still exists

2. It is similar to the above method, but I think it is more reliable

First, add ftpClient.setControlEncoding(" GBK "); This one, and then, transcode all the Chinese into "ISO-8859-1", as follows:

ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));

Answer: after testing, it still doesn't work. The reason why I say this method is more reliable is that please read on

First of all, let's talk about why to transcode:

Because in the FTP protocol, the file name is encoded as iso-8859-1, the directory name or file name needs transcoding.

The next question is what encoding we should convert to this format. Thus, there is a second solution -- converting the GBK format to ISO-8859-1. And, some say, it has to be. In fact, the reason they can say so, I think it is a complete coincidence. The real principle is that since the encoding format of FTP protocol is "ISO-8859-1", we really have to convert the format to 1, and then automatically convert to the system's own encoding format when the server receives the file. Therefore, the key is not to specify the format, but to determine the encoding format of FTP server. Therefore, if the encoding format of the FTP system is "GBK", the second method will definitely succeed. However, if the system is coded "UTF-8", it will still be scrambled. Therefore, we can only get the encoding format of the system through the code, and then convert it into the encoding format of ISO-8859-1. The acquisition method is as follows:

private static String encoding = System.getProperty("file.encoding");

The above code through their own tests, hope to solve the problem for everyone 1!


Related articles: