java FTP上传文件

1.需要上传文件至FTP,需要的jar包

    <dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.1</version>
    </dependency>

2.java代码

    @Test
    public void test2(){
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect("1.1.1.1",21);//设置地址和端口号
            ftp.login("aaa", "bbb");//用户名和密码
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);//上传文件类型 二进制文件
            int reply = ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){//检查连接是否有效
                System.out.println("error");
                return;
            }
            ftp.changeWorkingDirectory("/test");
            File file = new File("D:/jdbc.properties");
            FileInputStream fis = new FileInputStream(file);
            ftp.storeFile(file.getName(), fis);//关键代码,把流持久化到硬盘上
            fis.close();
            ftp.logout();
            ftp.disconnect();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

其实总体来看就是两个步骤,一个初始化FTPClient类,在来就是获取流,然后写到硬盘上.

原文地址:https://www.cnblogs.com/lishuaiqi/p/10299521.html