This article has shared with you two ways to upload and download Java FTP files for your reference. The specific content is as follows
The first method:
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's own API operation on FTP* @Title:Ftp.java * @author: Zhou Lingbin*/public class Ftp { /** * Local file name*/ private String localfilename; /** * Remote file name*/ private String remotefilename; /** * FTP client*/ private FtpClient ftpClient; /** * Server connection* @param ip Server IP * @param port Server port* @param user 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 methods to connect to the server*******/ //The first method//ftpClient = new FtpClient();// ftpClient.openServer(ip, port); //The second method ftpClient = new FtpClient(ip); ftpClient.login(user, password); //Set to binary transmission ftpClient.binary(); System.out.println("login success!"); if (path.length() != 0){ //Switch the directory on the remote system to the directory specified by the parameter path 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 file* @param localFile local file* @param remoteFile 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 { // Add the remote file to the output stream os = ftpClient.put(this.remotefilename); // Get the input stream of the local file File file_in = new File(this.localfilename); is = new FileInputStream(file_in); //Create 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(); } } } } /** * Download file* @param remoteFile Remote file path (server side) * @param localFile Local file path (client) * @author Zhou Lingbin* @date 2012-7-11 */ public void download(String remoteFile, String localFile) { TelnetInputStream is = null; FileOutputStream os = null; try { //Get the filename on the remote machine and use TelnetInputStream to transfer the file to the local area. 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 directory to connect to the FTP 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/haha.txt"; //Upload fu.upload(localfile, remotefile); fu.closeConnect(); }}
There is nothing to say about this method, it is relatively simple, and there is no problem of Chinese garbled code. It seems that there is a flaw and cannot operate large files. Interested friends can try it.
The second method:
public class FtpApche { private static FTPClient ftpClient = new FTPClient(); private static String encoding = System.getProperty("file.encoding"); /** * Description: Upload file to the FTP server* * @Version1.0 * @param url * FTP server hostname * @param port * FTP server port* @param username * FTP login account* @param password * FTP login password* @param path * FTP server saves the directory, if it is the root directory, it is "/" * @param filename * File name uploaded to the FTP server* @param input * Local file input stream* @return Return true successfully, otherwise 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, you can directly connect to the FTP server ftpClient.connect(url); // ftp.connect(url, port);// Connect to the FTP server // Log in to ftpClient.login(username, password); ftpClient.setControlEncoding(encoding); // Verify that the connection is successful reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { System.out.println("Connection failed"); 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 local files to the FTP server* */ public void testUpLoadFromDisk() { try { FileInputStream in = new FileInputStream(new File("E:/number.txt")); boolean flag = uploadFile("127.0.0.1", 21, "zlb","123", "/", "haha.txt", in); System.out.println(flag); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * Description: Download file from the FTP server* * @Version1.0 * @param url * FTP server hostname * @param port * FTP server port* @param username * FTP login account* @param password * FTP login password* @param remotePath * Relative path on the FTP server* @param fileName * File name to be downloaded* @param localPath * Path to save to local after download* @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 recommend using the following two sentences instead of * new String(remotePath.getBytes(encoding),"iso-8859-1") transcoding. * After testing, it cannot be passed. */// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);// conf.setServerLanguageCode("zh"); ftpClient.connect(url, port); // If the default port is used, you can directly connect to the FTP server by ftpClient.login(username, password);// Login// Set the file transfer type to binary ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); // Get the ftp login response code reply = ftpClient.getReplyCode(); // Verify that the login is successful if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); System.err.println("FTP server refused connection."); return result; } // Transfer to the FTP server directory to the specified directory ftpClient.changeWorkingDirectory(new String(remotePath.getBytes(encoding),"iso-8859-1")); // Get the file list 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; } /** * Download the file on the FTP server to the local * */ public void testDownFile() { try { boolean flag = downFile("127.0.0.1", 21, "zlb", "123", "/", "haha.txt", "D:/"); System.out.println(flag); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { FtpApche fa = new FtpApche(); fa.testDownFile(); }}
In this way, you need to pay attention to the problem of Chinese garbled code. If you set it incorrectly, the uploaded file name may be garbled code. Sometimes it cannot be uploaded at all. Of course, you will not prompt you because there is no exception. I have found many solutions online, and there are many different opinions. Almost all of them were copied from one version, and I have not been tested by myself. I have suffered a lot for this. It is roughly divided into the following two solutions:
1. Add the following three sentences to solve it
ftpClient.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
Answer: After testing, it simply doesn't work, the above problem still exists
2. It is similar to the above method, but I think this method is more reliable
First, add the sentence ftpClient.setControlEncoding("GBK"); and then, transcode all Chinese into "ISO-8859-1" format, as follows:
ftpClient.changeWorkingDirectory(new String(remotePath.getBytes("GBK"),"iso-8859-1"));
Answer: After testing, it still doesn't work. The reason I said this method is more reliable. Please continue reading.
First, let’s talk about why we need to transcode:
Because in the FTP protocol, the file name is specified to be encoded as iso-8859-1, the directory name or file name needs to be transcoded.
The next question is, what encoding should we convert to this format. Therefore, there is a second solution - converting the GBK format to ISO-8859-1 format. Moreover, some people also say that this must be done. In fact, I think the reason why they can say this is a complete coincidence. Its real principle is that since the encoding format specified by the FTP protocol is "ISO-8859-1", we really have to convert the format and then automatically convert it to the system's own encoding format when the server receives the file. Therefore, the key is not to specify the format, but to depend on the encoding format of the FTP server. Therefore, if the encoding format of the FTP system is "GBK", the second method will definitely succeed; however, if the encoding format of the system is "UTF-8", there will still be garbled code. Therefore, we can only obtain the encoding format of the system through the code, and then convert it to the encoding format of ISO-8859-1 through this encoding format. The acquisition method is as follows:
private static String encoding = System.getProperty("file.encoding");
All the above codes have been tested by yourself, I hope they can solve the problem for everyone!