Java FTP上传文件

发布时间 2023-08-21 13:54:00作者: 信铁寒胜

1、

public boolean upload(String ftpPath,List<String> fileNameList,List<String> files){
        boolean isSuccess = true;
        FTPClient client = new FTPClient();
        FileInputStream fis = null;
        try {
            client.connect(ftpId);
            client.login(ftpUserName, ftpPassword);
            client.setFileType(FTP.BINARY_FILE_TYPE);

            if (!client.changeWorkingDirectory(ftpPath)) {
                client.makeDirectory(ftpPath);
                client.changeWorkingDirectory(ftpPath);
            }
            for(int index =0;index<files.size();index++) {
                String filePath = files.get(index);
                fis = new FileInputStream(filePath);
                try {
                    String fileName = fileNameList.get(index);
                    fileName = new String(fileName.getBytes("GBK"),"iso-8859-1");
                    boolean isDelete = client.deleteFile(fileName);
                    isSuccess = client.storeFile(fileName, fis);
                    if (!isSuccess) {
                        return false;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    fis.close();
                }
                System.out.println("Uploading status is: " + isSuccess);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                client.logout();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }