java practice 3: upload data files to ftp server in java

Posted by hex on Tue, 04 Jan 2022 18:59:49 +0100

1: Introduction to ftp

File Transfer Protocol (FTP) is a set of standard protocols used for file transmission on the network. It works in the seventh layer of OSI model and the fourth layer of TCP model, that is, the application layer. TCP transmission is used instead of UDP. The customer needs to go through a "three-time handshake" before establishing a connection with the server The process ensures that the connection between the client and the server is reliable and connection oriented, providing a reliable guarantee for data transmission.
FTP allows users to operate as files (such as file addition, deletion, modification, query, transmission, etc.) communicate with another host. However, users do not really log in to the computer they want to access and become full users. FTP programs can be used to access remote resources to realize users' round-trip transmission of files, directory management, access to e-mail, etc., even if the computers of both sides may be equipped with different operating systems And file storage.

1.1: workflow

When transferring files, the FTP client program first establishes a connection with the server, and then sends commands to the server. After receiving the command, the server responds and executes the command. FTP protocol has nothing to do with the operating system. Programs on any operating system can transmit data to each other as long as they comply with FTP protocol

2: Open ftp service in windows

You can open an ftp service on your computer for testing.
1: Open control panel - programs - start or close windows functions
Find Internet information service check ✔ Among them, ftp server, web management and World Wide Web service.
The system will install IIS service manager. The installation process may take a few minutes.

2: Return to the computer desktop, right-click "computer", click management, and enter the computer management interface. Here, we can see the IIS service just added. The next operation is like adding a website on the VPS host. Select IIS Service - Website - right click to add FTP site

3: Set basic ftp information. The path is the working path of the remote connection

Select the IP address of this machine. If SSL is not secret related, you can select none.

Here, you can set the permissions like this before modifying them. Click finish.

After saving, you can see the added ftp service. Multiple can be opened in this way.

4: Attention
To connect to FTP through java program, I create a new FTP user, ftptest, password: 123456, as shown below

Note that √ must be cancelled here. Confirm to complete the creation, and then modify the FTP server settings to add this specific user.

Click the created ftp name - ftp authentication - modify identity authentication to prohibit anonymous identity


Return to the initial page and add the user just created. If the user created is checked, the addition may not succeed.

Enter the user name and password you just created and finish

How to test whether the newly created user is effective? There are many methods. The common ones are the CMD command line and the one described below
Turn on my computer and type it at the top
FTP: / + IP address set before FTP
My is FTP: / 169.254 187.243 enter
Enter the user and password to log in

3: Developing connection ftp with java

org.apache.common.io provides the development of FTP and introduces the following dependencies

     <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.5</version>
    </dependency>

3.1: ftp tools

Connect to ftp service

public class FtpClient {
    private final static Logger LOGGER = LoggerFactory.getLogger(FtpClient.class);
    /**
     * FTP Service address
     */
    private static String FTP_IP;
    /**
     * FTP Port number
     */
    private static Integer FTP_PORT;
    /**
     * FTP user name
     */
    private static String FTP_USER;
    /**
     * FTP password
     */
    private static String FTP_PASSWORD;
    /**
     * FTP Root path
     */
    private static String FTP_PATH;
    /**
     * Mapped drive letter
     */
    private static String FTP_DRIVELETTER;
    private static FTPClient ftpClient;

    static {
        try {
            Properties properties = new Properties();
            InputStream inputStream = FtpClient.class.getClassLoader().getResourceAsStream("ftp-config.properties");
            properties.load(inputStream);
            FTP_IP = properties.getProperty("FTP_IP");
            FTP_PORT = Integer.valueOf(properties.getProperty("FTP_PORT"));
            FTP_USER = properties.getProperty("FTP_USER");
            FTP_PASSWORD = properties.getProperty("FTP_PASSWORD");
            FTP_PATH = properties.getProperty("FTP_PATH");
            FTP_DRIVELETTER = properties.getProperty("FTP_DRIVELETTER");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static FTPClient getFTPConnection() {
        ftpClient = new FTPClient();
        try {
            //connect
            ftpClient.connect(FtpClient.FTP_IP, FtpClient.FTP_PORT);
            //Set encoding
            ftpClient.setControlEncoding("UTF-8");
            //Set transfer file type
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //Sign in
            ftpClient.login(FtpClient.FTP_USER, FtpClient.FTP_PASSWORD);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                LOGGER.info("==============Not connected to FTP,Wrong user name or password=================");
                //connection denied
                ftpClient.disconnect();
            } else {
                LOGGER.info("==============connection to FTP success=================");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            LOGGER.info("==============FTP of IP Address error==============");
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info("==============FTP Port error==============");
        }
        return ftpClient;
    }

    public static void closeConnect() {
        LOGGER.warn("close ftp The server");
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ftp tool class to upload and download files

public class FTPUtils {
    /**
     * Upload single file to remote
     *
     * @param ftpPath        route
     * @param uploadFileName file name
     * @param input          Input stream
     * @return
     */
    public static boolean uploadFile(String ftpPath, String uploadFileName, InputStream input) {
        boolean issuccess = false;
        FTPClient ftpClient = null;
        try {
            ftpClient = FtpClient.getFTPConnection();

            //Switch to working directory

            if (!ftpClient.changeWorkingDirectory(ftpPath)) {
                ftpClient.changeWorkingDirectory("/");
                String[] dirs = ftpPath.split("/");
                for (String dir : dirs) {
                    ftpClient.makeDirectory(dir);
                    ftpClient.changeWorkingDirectory(dir);
                }
            }

            ftpClient.enterLocalPassiveMode();//
            //Write the file to the remote file name; Input stream
            boolean storeFile = ftpClient.storeFile(uploadFileName, input);
            if (!storeFile) {
                return issuccess;
            }
            input.close();
            ftpClient.logout();
            issuccess = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return issuccess;
    }

    private String inputStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer stringBuffer = new StringBuffer();
        String oneLine = "";
        try {
            while ((oneLine = bufferedReader.readLine()) != null) {
                stringBuffer.append(oneLine);
            }
            return stringBuffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

3.2: testing

Data written successfully

    public static void main(String[] args) {
        String str = "test";
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(str.getBytes());
        FTPUtils.uploadFile("/remote", "test.txt", inputStream);
    }

Topics: Java network server