version

  • Linux for CentOS7. X
  • Java for jdk8

FTP

To prepare something

Prepare what you need

1. Install FTP (VSFTPD) on Linux

2. Create an FTP user on Linux

  • Useradd account passwd account #(enter) Set the password for the user -- enter the password twice, note that the password is not displayed, enter the correct press enter userdel account -- delete tail /etc/passwd -- view all accountsCopy the code

2. Create projects

3, import corresponding dependencies!!

<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>
Copy the code

Creating a test class

Simple native Commons-net to get FTP connections

public class FTPUtil {
  public static void main(String[] args) throws IOException {
    FTPClient ftp = null;
    try {
      ftp = getFTPClient();
      System.out.println(ftp);
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      if(ftp ! =null) {
        // Disconnect the connectionftp.logout(); }}}public static FTPClient getFTPClient(a) {
    FTPClient ftp = null;
    try {
      ftp = new FTPClient();
      // Connect to the FPT server and set the IP address and port number
      ftp.connect("".21);
      // Set the user name and password
      ftp.login(""."");
      // Set connection timeout to 5000 ms
      ftp.setConnectTimeout(5000);
      // Set the Chinese code set to prevent Chinese garbled characters
      ftp.setControlEncoding("UTF-8");
      if(! FTPReply.isPositiveCompletion(ftp.getReplyCode())) { System.out.println("Not connected to FTP, wrong username or password");
        ftp.disconnect();
      } else {
        System.out.println("FTP connection successful"); }}catch (SocketException e) {
      e.printStackTrace();
      System.out.println("FTP IP address may be incorrect. Please configure it correctly.");
    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("FTP port is incorrect. Please configure it correctly.");
    }
    returnftp; }}Copy the code

The test results

The output reference address is OK, but things are not so good results, the above result is I configured and then run the effect

Start writing normal code

preface

1, you have to make the FTP connection successfully Please go down to find the reason for the error. I have listed several reasons below

Preparing project requirements

POM depends on

<! Java toolkit -->
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.7.2</version>
</dependency>
<! -- FTP connection -->
<groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.8.0</version>
</dependency>
Copy the code

hutool

  • Is a Java packaged tool class which contains a lot of tool classes, website: www.hutool.cn/
  • Why use this utility class because there’s no need to write code all over again, to avoid picking a utility class on the web and hitting a brick wall, and to simply use one

The test code

public static void main(String[] args){
  Ftp ftp = null;
  try {
    ftp = new Ftp("ip"The FTP port is common21."Username"."Password");
    System.out.println(ftp);
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (null! = ftp) {try {
        // Release resources
        ftp.close();
      } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

The connection is successful

Commonly used method

Specific use to hutool see documents: apidoc.gitee.com/dromara/hut…

CD () -- change the directory close() -- free the resource PWD () -- get the current directory upload() -- upload files download() -- download files delDir() -- delete all files in the specified directory delFile() -- Delete the file ftp.getClient() -- get the FTPClient objectCopy the code

Upload a file

public static void main(String[] args){
  Ftp ftp = null;
  try {
    // Create the account and password
    ftp = new Ftp("ip".21."Account"."Password");
    // Where to go is a folder made up of /home/ account names
    // what is the same as the login account /home/ XXX
    System.out.println(ftp.pwd());
    /* Upload file method first parameter: upload path second parameter: upload file name third parameter: local file path */
    boolean upload = ftp.upload(". /"."aaa.md".new File("E:\\ notes \\Linux\ Linux command.md"));
    System.out.println(upload);
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (null! = ftp) {try {
        ftp.close();
      } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

The effect

Appears in the code above. /Is the current directory,pwd()Can get the path of the current directory,cd()Enter the specified path,

Note: Uploading to the specified folder must be the owner of the current login FTPD. Otherwise, uploading fails.

The download file

public static void main(String[] args){
  Ftp ftp = null;
  try {
    ftp = new Ftp("".21.""."");
    System.out.println(ftp.pwd());
    /** Upload method first parameter: download path second parameter: download file name third parameter: local file path **/
    ftp.download(". /"."aaa.md".new File("E:\\1"));
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if (null! = ftp) {try {
        ftp.close();
      } catch(IOException e) { e.printStackTrace(); }}}}Copy the code

You can also use the ftp.getClient() method to get the FTPClient object and call some other methods in FTPClient.

Hutool is only an encapsulation of FTPClient, and it is only a demo to upload a certain file. It cannot upload a specified folder, and the way to upload a specified folder is also very simple, which is to upload files in the folder through recursive calls

Note:

  • I sometimes upload and download fake dead in is always running no response results, download data is 0KB, also ask big guy for advice
  • In the case of the specified user login, the directory for uploading files must be the user’sOwner. Owning groupDownload files must belong to the logged-in userOwner. Owning group.

SFTP

preparation

1. Import the required dependencies

<! -- SFTP required -->
<dependency>
  <groupId>com.jcraft</groupId>
  <artifactId>jsch</artifactId>
  <version>0.1.54</version>
</dependency>
<! -- Hutool -->
<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.7.2</version>
</dependency>
Copy the code

2. Write code

public static void main(String[] args) {
  Sftp sftp = null;
  try {
    /** SFTP is a part of SSH, so the port uses 22 **/
    sftp = new Sftp("ip".22."Username"."Password");
    /** first parameter: upload path second parameter: upload file name, what is the name of the uploaded file **/
    boolean upload = sftp.upload("/a".new File("E:\\1\\467.txt"));
    System.out.println(upload);
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if(sftp ! =null) { sftp.close(); }}}Copy the code

download

public static void main(String[] args) {
  Sftp sftp = null;
  try {
    sftp = new Sftp("ip".22."Username"."Password");
     /** First argument: download file second argument: download file **/
    sftp.download("/a/467.txt".new File("E:\\1\\123.txt"));
  } catch (Exception e) {
    e.printStackTrace();
  } finally {
    if(sftp ! =null) { sftp.close(); }}}Copy the code

Note: SFTP is uploaded based on JSCH packages and Hutool is just a utility class. You can also use sftp.getClient() to get JSCH objects for more operations.

Port 22 is not blocked because SSH access is enabled on port 22 by default

FTP troubleshooting error occurs

misarrangement

1. (Ali/Tencent) Cloud security policy port is not open

2. (Ali/Tencent) The server firewall of the cloud is open, but the corresponding port is not open

The image above shows the effect of the firewall being off

Above is the open state

Ps :(ali/Tencent) cloud server is closed by default firewall

Operation about server firewall

Take out my old guard book Liunx command

Run the systemctl stop firewalld.service command to disable the firewall: systemctl start firewalld.service To restart the firewall: Systemctl restart firewalld.service Disables automatic startup upon system startup: systemctl disable firewalld.service Enables startup upon system startup: Systemctl enable firewalld.service Displays the firewall status: systemctl status firewalld Displays the open ports of the firewall: iptables -l -n centos7 Displays all firewall information: Firewall-cmd --list-all centos7 Run the firewall-cmd --list-ports command to view information about the ports opened by the firewallCopy the code

This is required if you want the firewall to be on and allow port access

Adding an Open Port

Firewall-cmd --add-port= port/TCP --zone=public --permanent
#Refresh to make the configuration take effect
firewall-cmd  --reload
#Description:
#- zone# scope
#- add - port = 80 / TCPAdd a port in the format of port/protocol
#- permanent Takes effect permanently. If this parameter is not specified, the parameter becomes invalid after the restart
Copy the code

Deleting an Open Port

Firewall-cmd --remove-port= port/TCP --zone=public --permanent
#Refresh to make the configuration take effect
firewall-cmd  --reload
Copy the code

Check whether the port is allowed

firewall-cmd --query-port=8080/tcp --zone=public
#Return yes or no
Copy the code

Note: this second only to the server firewall port open, if the (Ali/Tencent) cloud security policy port is not open can not access the connection.

summary

Basically these questions, if you have cerebral palsy in FTP set blacklist, forget I said.

Summary:

  • I see some stuff on the Internet, tooFTPUtility classes, but basic upload files we usehutoolIn the utility class is ok, save to avoid writing repeated code, he does not upload the folder method, upload the entire folder can be used in the form of recursive upload, after the need to own encapsulation.
  • One of the problems encountered is in useFTPUpload/download, will lead to a suspended animation state, is always running without results, the method on the net also tried is useless, before I can upload, is sometimes suddenly will be so, have the knowledge of the return please teach teach!!