Windows builds FTP server and JAVA realizes read-write function

Posted by trackz on Thu, 16 Dec 2021 08:24:35 +0100

catalogue

Blogger introduction

💂 Personal home page: Suzhou program white
💂 Individual communities: CSDN programs across the country
🤟 Introduction to the author: member of China DBA Alliance (ACDU), administrator of CSDN program ape (yuan) gathering places all over the country. Currently engaged in industrial automation software development. Good at C#, Java, machine vision, underlying algorithms and other languages. The July software studio was established in 2019 and registered with Suzhou Kaijie Intelligent Technology Co., Ltd. in 2021
💬 If the article is helpful to you, you are welcome to pay attention, like, collect (one click, three links) and subscribe to some columns such as C#, Halcon, python+opencv, VUE, interviews with major companies, etc
🎗️ Undertake software app, applet Application development in key industries such as website development (SaaS, PaaS, CRM, HCM, bank core system, regulatory submission platform, system construction, artificial intelligence assistant), big data platform development, business intelligence, app development, ERP, cloud platform, intelligent terminal, product solutions. Test software product testing, application software testing, test platform and products, test solutions. Maintenance of operation and maintenance database (SQL Server, Oracle, MySQL), operating system maintenance (Windows, Linux, Unix and other common systems), server hardware equipment maintenance, network equipment maintenance, operation and maintenance management platform, etc. operation services, IT consulting, IT services and business process outsourcing (BPO), cloud / infrastructure management, online marketing, data collection and annotation, content management and marketing, design services, localization, intelligent customer service, big data analysis, etc.
💅 If you have any questions, you are welcome to send a private letter and will reply in time
👤 Micro signal: stbsl6, WeChat official account: Suzhou program whiten
🎯 Those who want to join the technical exchange group can add my friends. The group will share learning materials

Enable FTP function

First open control panel – > programs – > enable or disable Windows features:

Check FTP service, web management tool and World Wide Web Service:


Click Finish to wait for it to take effect:

Release port

Open the Windows firewall – > allow applications to pass through the firewall – > click change settings and check the public and private of the FTP server:

Restart the computer

After completing the above operations, restart the computer.

Add FTP access user

Optional. If you set anonymous access to FTP or directly use existing users in Windows, you don't need to create users.

Open the computer management function – > local users and groups, select users, and right-click new users:


Set the user name and password. Check that the password cannot be modified and will never expire. Uncheck other and click Create:

Add FTP site

Open the computer management function, find Internet Information Services in the service, select the user on the left, and right-click to add an FTP site:

Customize the site name and select the file path to be shared by FTP:

Set the IP address as the local IP address. The default port is 21. If there is no SSL, select no SSL:

Check that authentication is basic, that authorization is the specified user, that users can access, and that permissions are write and read (this can be customized according to the specific situation. If you want to set anonymous access, check anonymous, and then allow access. Select all users), and then click OK:

Local access test

File manager input ip address plus port:

Right click and select login (if the login interface does not pop up, anonymous access does not have this operation)

Enter the user name and password and click login:

Normal access:

Modify the file name to test whether it can be modified:

Test remote access FTP (in the same network environment):

After completing the above steps, you can access it.

Modify FTP settings

Open the computer management function, find Internet Information Services in the service, expand the computer user – > website, double-click the created FTP server, and then you can make various modifications:

  • Add all user access:

Double click FTP authentication to enable anonymous authentication:

Double click the FTP authorization rule and right-click to add an allow rule:

Select all users, check the read and write permissions, and click OK. You don't need to enter a password when accessing again.

Java integration FTP code implementation

FTP file deletion implementation:

package org.example;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.File;
import java.io.IOException;
/**
* @author Suzhou program Dabai
* @create 2021/12/16
* @desc File deletion (the function of deleting subfolders in the path has not been realized yet)
*/
public class DeleteFTP {
    /**
     * @param pathName     ftp path where the file / directory is to be deleted
     * @param fileName     The file name of the ftp where the file is to be deleted
     * @param ftpClient    FTPClient object
     */
    public void deleteFTP(String pathName, String fileName, FTPClient ftpClient) {

        try {
            ftpClient.changeWorkingDirectory(pathName);// Jump to file directory
            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission
            if (fileName != null && fileName != "") {
                //The file name is not empty. Delete the specified file
                ftpClient.deleteFile(pathName + File.separator + fileName);
                System.out.println("Delete succeeded");
            } else {
                //The file name is empty. Delete all files under the path
                System.out.println("Deleting");
                //Delete file
                FTPFile[] files = ftpClient.listFiles();//Get the file collection under the directory
                for (FTPFile file : files) {

                    if (file.isFile()) {
                        //If it is judged as a file, delete it directly
                        ftpClient.deleteFile(pathName + File.separator + file.getName());
                        System.out.println(file + ": Delete operation completed");
                    }
                    if (file.isDirectory()) {
                        /*There is a problem. It is recommended to use thread optimization
                        //Determine whether it is a folder, and recursively delete the files in the subfolder
                        deleteFTP(pathName + File.separator + file.getName(), null, ftpClient);
                        */
                    }
                }
                //remove folders
                ftpClient.removeDirectory(pathName);
                System.out.println("Delete operation completed");
            }
        } catch (Exception e) {
            System.out.println("Deletion failed");
            e.printStackTrace();
        } finally {
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
      }
    }

FTP file download implementation:

package org.example;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author Suzhou program Dabai
* @create 2021/12/16
* @desc File download (the file function in the sub file in the download path has not been realized yet)
*/
public class DownloadFTP {
    /**
     * @param pathName     ftp path of the file to be downloaded
     * @param fileName     The file name of the ftp where the file is to be downloaded
     * @param downloadPath Path saved after file download
     * @param ftpClient    FTPClient object
     */
    public void downLoadFTP(String pathName, String fileName, String downloadPath, FTPClient ftpClient) {

        OutputStream outputStream = null;
        try {
            ftpClient.changeWorkingDirectory(pathName);// Jump to file directory
            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission

            if (fileName != null && fileName != "") {
                //The file name is not empty. Download the specified file
                File filePath = new File(downloadPath);
                if (!filePath.exists()) {
                    filePath.mkdir();//Directory does not exist, create directory
                }
                outputStream = new FileOutputStream(new File(downloadPath + File.separator + fileName));
                ftpClient.retrieveFile(fileName, outputStream);
                System.out.println("Download operation completed");
            } else {
                FTPFile[] files = ftpClient.listFiles();//Get the file collection under the directory
                //The file name is empty. All files in the download path (excluding folders)
                for (FTPFile file : files) {
                    File filePath = new File(downloadPath);
                    if (!filePath.exists()) {
                        filePath.mkdir();//Directory does not exist, create directory
                    }
                    File downloadFile = new File(downloadPath + File.separator + file.getName());
                    outputStream = new FileOutputStream(downloadFile);
                    ftpClient.retrieveFile(file.getName(), outputStream);

                    System.out.println("Download operation completed:" + downloadFile);
                }
            }

        } catch (Exception e) {
            System.out.println("Download failed");
            e.printStackTrace();
        } finally {
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Connection FTP code implementation:

package org.example;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.net.MalformedURLException;
/**
* @author Su program Dabai
* @create 2021/12/16
* @desc Link to FTP service
*/

public class InitFTP {

    //ftp server IP
    private static final String host = "127.0.0.1";
    //The ftp server port number defaults to 21
    private static final Integer port = 21;
    //ftp login account
    private static final String username = "ahzoo";
    //ftp login password
    private static final String password = "123456";

    public void initFtpClient(FTPClient ftpClient) {
        ftpClient.setControlEncoding("utf-8"); //Set encoding
        try {
            System.out.println("on connection FTP The server:" + host + ":" + port);
            ftpClient.connect(host, port); //Connect to ftp server
            ftpClient.login(username, password); //Log in to ftp server
            int replyCode = ftpClient.getReplyCode(); //Successfully logged in to the server
            if(!FTPReply.isPositiveCompletion(replyCode)){
                System.out.println("FTP Server connection failed:" + host + ":" + port);
            }
            System.out.println("FTP Server connection succeeded:" + host + ":" + port);
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Implementation of ftp path code where the mobile file is located:

package org.example;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.File;
import java.io.IOException;
/**
* @author Su program Dabai
* @create 2021/12/16
* @desc File move / rename
*/
public class MoveFTP {
    /**
     * @param pathName     ftp path where the file is to be moved
     * @param fileName     The file name of the ftp where the file is to be moved
     * @param movePath     Path after file movement
     * @param moveName     The file name after the file is moved (only move without renaming if it is consistent with the source file, and move + rename if it is inconsistent)
     * @param ftpClient    FTPClient object
     */
    public void moveFTP(String pathName, String fileName, String movePath, String moveName, FTPClient ftpClient) {
        try {
            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission
            if (!ftpClient.changeWorkingDirectory(movePath)) {
                //Create target directory when jump to target path fails
                ftpClient.makeDirectory(movePath);
            }
            if (moveName != null && moveName != "") {
                ftpClient.changeWorkingDirectory(pathName);// Jump back to the directory where you want to operate
                //The file name after the move is not empty. Move the target file
                //ftpClient. Rename (old file name, new path)
                ftpClient.rename(fileName, movePath + File.separator + moveName);
                System.out.println("File move operation completed:" + movePath + File.separator + moveName);
            } else {
                //The file name after the move is empty, and all files in the target path are moved

                ftpClient.changeWorkingDirectory(pathName);// Jump back to the directory where you want to operate
                FTPFile[] files = ftpClient.listFiles();//Get the file collection under the directory

                for (FTPFile file : files) {
                    ftpClient.rename(file.getName(), movePath + File.separator + file.getName());
                    System.out.println("Move operation completed:" + file.getName());
                }
            }

        } catch (Exception e) {
            System.out.println("Move failed");
            e.printStackTrace();
        } finally {
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }

    }

}

Read the ftp path code of the file to achieve:

package org.example;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.*;
/**
 * @author Su program Dabai
 * @create 2021/12/16
 * @desc File reading (the function of reading files in sub files in the path has not been realized yet)
 */
public class ReadFTP {
    /**
     * @param pathName     ftp path where the file is to be read
     * @param fileName     The file name of the ftp where the file is to be read
     * @param ftpClient    FTPClient object
     */
    public void readFTP(String pathName, String fileName, FTPClient ftpClient) {

        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            System.out.println(pathName);
            ftpClient.changeWorkingDirectory(pathName);// Jump to file directory
            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission

            if (fileName != null && fileName != "") {
                //The file name is not empty. Read the specified file
                inputStream = ftpClient.retrieveFileStream(fileName);
                reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String fileL;
                StringBuffer buffer = new StringBuffer();
                while(((fileL=reader.readLine()) != null)){
                    buffer.append(fileL);
                }
                System.out.println(fileName + ":" + buffer.toString());

            } else {
                FTPFile[] files = ftpClient.listFiles();//Get the file collection under the directory
                //The file name is empty. Read all files under the path (excluding folders)
                System.out.println(files);
                for (FTPFile file : files) {
                    System.out.println(file.getName());
                    inputStream = ftpClient.retrieveFileStream(file.getName());
                    System.out.println(inputStream);
                    reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    String fileL = null;
                    StringBuffer buffer = new StringBuffer();

                    while(((fileL=reader.readLine()) != null)){
                        buffer.append(fileL + "\n");
                    }
                    System.out.println(file + ":" + buffer.toString());
                    //retrieveFileStream uses a stream. It needs to be released, otherwise it will return a null pointer
                    ftpClient.completePendingCommand();
                }
            }

        } catch (Exception e) {
            System.out.println("read failure");
            e.printStackTrace();
        } finally {
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

Implementation of path code uploaded to ftp server:

package org.example;

import org.apache.commons.net.ftp.FTPClient;

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

/**
 * @author Su program Dabai
 * @create 2021/12/16
 * @desc File upload
 */
public class UploadFTP {
    /**
     * @param pathName The path to upload the file to the ftp server
     * @param fileName The name of the file uploaded to the ftp server
     * @param originPath The path where the file to be uploaded is located (absolute path)
     **/
    public void uploadFile(String pathName, String fileName, String originPath, FTPClient ftpClient){
        InputStream inputStream = null;
        try{
            System.out.println("File transfer in progress");
            inputStream = new FileInputStream(new File(originPath));//Convert text data to an input stream

            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);//Input as binary file
            ftpClient.makeDirectory(pathName);//Create the target path on the ftp server
            ftpClient.changeWorkingDirectory(pathName);//Switch to target path
            ftpClient.enterLocalPassiveMode();//Open port
            ftpClient.storeFile(fileName, inputStream);//Start uploading. inputStream represents the data source.
            //ftpClient.storeFile(new String(fileName.getBytes("UTF-8"),"ISO-8859-1") inputStream);
            System.out.println("File upload operation completed");
        }catch (Exception e) {
            System.out.println("File upload failed");
            e.printStackTrace();
        }finally{
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Path code implementation for writing text to ftp server:

package org.example;

import org.apache.commons.net.ftp.FTPClient;

import java.io.*;
/**
 * @author Su program Dabai
 * @create 2021/12/16
* @desc Text writing
*/
public class WriteFTP {
    /**
     * @param pathName Path to write text to ftp server
     * @param fileName The name of the ftp server to which the text is written
     * @param contentText Text data to write
     **/
    public void writeFile(String pathName, String fileName, String contentText, FTPClient ftpClient){
        InputStream inputStream = null;
        try{
            System.out.println("Start write operation");
            inputStream = new ByteArrayInputStream(contentText.getBytes());//Convert text data into input stream, and avoid Chinese garbled code through getBytes() method

            ftpClient.enterLocalPassiveMode(); //Set passive mode transmission
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);//Input as binary file
            ftpClient.makeDirectory(pathName);//Create the target path on the ftp server
            ftpClient.changeWorkingDirectory(pathName);//Switch to target path
            ftpClient.enterLocalPassiveMode();//Open port
            ftpClient.storeFile(fileName, inputStream);//Start writing, inputStream represents the data source.

            System.out.println("Text write operation completed");
        }catch (Exception e) {
            System.out.println("Text writing failed");
            e.printStackTrace();
        }finally{
            //Close connection
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

🌟 Author related articles and resource sharing 🌟

🌟 Let the world have no technology that can't be learned 🌟
Learning C# is no longer a difficult problem
🌳 C# getting started to advanced tutorial 🌳
Relevant C# practical projects
👉 C#RS232C communication source code 👈
👉 C # entrusted data transmission 👈
👉 C# Modbus TCP source code 👈
👉 C# warehouse management system source code 👈
👉 C# Omron communication Demo 👈
👉 C#+WPF+SQL is the camera system of vehicle management station currently on-line in a city 👈
👉 2021C# and Halcon vision common framework 👈
👉 In the vision project in 2021, C# is used to complete the communication between Mitsubishi PLC and host computer 👈
👉 VP joint open source deep learning programming (WPF) 👈
✨ For C# project, please check your home page ✨
🌟 Machine vision, deep learning 🌟
Learning machine vision and deep learning are no longer difficult problems
🌌 Halcon introduction to mastery 🌌
🌌 In depth learning materials and tutorials 🌌
Machine vision, deep learning and actual combat
👉 2021 C#+HALCON vision software 👈
👉 In 2021, C#+HALCON will realize template matching 👈
👉 C# integrates Halcon's deep learning software 👈
👉 C# integrated Halcon's deep learning software with [MNIST example] data set 👈
👉 C # halcon WPF open source form control that supports equal scaling and dragging 👈
👉 Labview and HALCON in 2021 👈
👉 Labview and Visionpro in 2021 👈
👉 Automatic identification module of brake pad thickness of EMU based on Halcon and VS 👈
✨ For machine vision and in-depth learning, welcome to your personal home page ✨
🌟 Java, database tutorials and projects 🌟
Learning Java and database tutorials is no longer a difficult problem
🍏 Introduction to JAVA advanced tutorial 🍏
🍏 Getting started with database to advanced tutorial 🍏
Actual combat of Java and database projects
👉 Java classic nostalgic bully web game console source code enhanced version 👈
👉 js+css similar web version Netease music source code 👈
👉 Java property management system + applet source code 👈
👉 JavaWeb Home Electronics Mall 👈
👉 Design and implementation of JAVA hotel room reservation management system SQLserver 👈
👉 Research and development of JAVA library management system MYSQL 👈
✨ For Java, database tutorials and project practice, welcome to your personal home page ✨
🌟 Share Python knowledge, explain and share 🌟
Learning Python is no longer a difficult problem
🥝 Python knowledge and project column 🥝
🥝 "Python detects the tremble, concerns the account number tiktok". 🥝
🥝 Teach you how to install and use Python+Qt5 🥝
🥝 Q & A on the fundamentals of python Programming in 10000 words to Xiaobai 🥝
🥝 Python drawing Android CPU and memory growth curve 🥝
🥝 < ☀️ Suzhou program big white uses ten thousand words to analyze Python Network Programming and Web programming ☀️ < ❤️ Remember to collect ❤️>>🥝
About Python project practice
👉 Python library management system based on Django 👈
👉 Python management system 👈
👉 Nine commonly used python crawler source codes in 2021 👈
👉 python QR code generator 👈
✨ For Python tutorial and project practice, welcome to your personal home page ✨
🌟 Share the interview questions and interview process of major companies 🌟
It's not difficult to succeed in an interview
🍏 The latest VUE interview questions of gold, nine and silver in 2021 ☀️ < ❤️ Remember to collect ❤️>>🍏
🍏 As long as you read 10000 words carefully ☀️ Linux Operating System Basics ☀️ Hang the interviewer every minute< ❤️ Remember to collect ❤️>>🍏
🍏 < ❤️ Give Xiaobai a comprehensive explanation of the basics of python Programming in 10000 words ❤️ < 😀 Remember to collect, or it will disappear 😀>>🍏
✨ About the interview questions and interview process of major companies, you are welcome to view your personal home page ✨

💫 Click to receive the data directly 💫

There are all kinds of learning materials, interesting programming projects and hard to find resources. ​ ​

❤️ Pay attention to the official account of Suzhou procedures ❤️
👇 👇👇

Topics: Java Windows Operation & Maintenance server