开发者社区> 问答> 正文

ftpClient 上传文件 ftp.storeFile(filename, input); 无反应

/**
* Description: 向FTP服务器上传文件
* @Version      1.0
* @param url FTP服务器hostname
* @param port  FTP服务器端口
* @param username FTP登录账号
* @param password  FTP登录密码
* @param path  FTP服务器保存目录
* @param filename  上传到FTP服务器上的文件名
* @param input   输入流
* @return 成功返回true,否则返回false *
*/
public static boolean uploadFile(String url,// FTP服务器hostname
int port,// FTP服务器端口
String username, // FTP登录账号
String password, // FTP登录密码
String path, // FTP服务器保存目录
String filename, // 上传到FTP服务器上的文件名
InputStream input // 输入流
){
boolean success = false;
FTPClient ftp = new FTPClient();
ftp.setControlEncoding("GBK");
try {
int reply;
ftp.connect(url, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.makeDirectory(path);
ftp.changeWorkingDirectory(path);
//ftp.enterLocalPassiveMode();
//ftp.storeFile(filename, input);
ftp.storeFile(new String(("/"+filename).getBytes("UTF-8"),"iso-8859-1"),input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}

/**
* 将本地文件上传到FTP服务器上 *
*/
public static void upLoadFromProduction(String url,// FTP服务器hostname
int port,// FTP服务器端口
String username, // FTP登录账号
String password, // FTP登录密码
String path, // FTP服务器保存目录
String filename, // 上传到FTP服务器上的文件名
String orginfilename // 输入流文件名
  ) {
try {
FileInputStream in = new FileInputStream(new File(orginfilename));
boolean flag = uploadFile(url, port, username, password, path,filename, in);
System.out.println(flag);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
upLoadFromProduction("192.168.13.32", 21, "hanshibo", "han", "韩士波测试", "hanshibo.doc", "E:/temp/H2数据库使用.doc");
}

展开
收起
kun坤 2020-06-06 11:54:37 1176 0
1 条回答
写回答
取消 提交回答
  • 请帮忙看哈,谢谢啦!######等会我给你一个我在项目中实际用过的######

    package com.va.util;

    import ch.qos.logback.classic.Logger; import com.zoki.util.Charset; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import org.apache.commons.net.io.CopyStreamListener; import org.slf4j.LoggerFactory;

    /** * FTP连接会话 * * @author zhoukai */ public class FtpSession {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(FtpSession.class);
    
    private final FTPClient ftpClient;
    
    /**
     * 获取FTPClient对象
     *
     * @param ftpHost FTP主机服务器
     * @param ftpPassword Ftp 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort FTP端口 默认为21
     * @param ftpServerDic FTP服务器保存目录
     * @param listener
     * @return
     */
    private FTPClient getFTPConnection(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword) throws IOException {
        FTPClient ftp = new FTPClient();
        ftp.connect(ftpHost, ftpPort);// 连接FTP服务器
        ftp.login(ftpUserName, ftpPassword);// 登陆FTP服务器
        ftp.setControlEncoding("UTF-8");
        ftp.setCharset(Charset.utf8);
        ftp.setKeepAlive(true);
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //设置被动模式传输  
        ftp.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            logger.info("未连接到FTP,用户名或密码错误。");
            ftp.disconnect();
        } else {
            logger.info("FTP连接成功。");
        }
    

    // try { // // } catch (SocketException e) { // logger.error("FTP的IP地址可能错误,请正确配置。\n", e); // } catch (IOException e) { // logger.error("FTP的端口错误,请正确配置。\n", e); // } return ftp; }

    /**
     * 构造方法
     *
     * @param ftpHost ftp地址
     * @param ftpPort ftp开放的端口
     * @param ftpUserName ftp登录用户名
     * @param ftpPassword ftp登录密码
     * @param listener
     * @throws java.io.IOException
     */
    public FtpSession(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, CopyStreamListener listener) throws IOException {
        ftpClient = this.getFTPConnection(ftpHost, ftpPort, ftpUserName, ftpPassword);
        ftpClient.setCopyStreamListener(listener);
    }
    
    private String changeFileNameCharset(String fileName) {
        return new String(fileName.getBytes(), Charset.utf8);
    }
    
    /**
     * 改变FTP工作目录
     *
     * @param toRemotePath FTP当前的工作目录
     * @return true成功选择工作目录
     * @throws IOException
     */
    public boolean changeWorkingDirectory(String toRemotePath) throws IOException {
        if (ftpClient == null) {
            return false;
        }
        if (!ftpClient.isConnected()) {
            return false;
        }
        return ftpClient.changeWorkingDirectory(toRemotePath);
    }
    
    /**
     * 上传文件,需要制定上传的目录,调用changeWorkingDirectory方法
     *
     * @param fileName 文件名
     * @param is 文件数据流
     * @return true上传成功
     * @throws IOException IO错误
     */
    public boolean uploadFile(String fileName, InputStream is) throws IOException {
        if (ftpClient == null) {
            return false;
        }
        if (!ftpClient.isConnected()) {
            return false;
        }
        boolean bool = ftpClient.storeFile(changeFileNameCharset(fileName), is);
        is.close();
        return bool;
    }
    
    /**
     * 上传单个文件
     *
     * @param fileName 上传的文件名
     * @param is 上传的文件数据流
     * @param toRemotePath ftp远程目录
     * @return true正确的上传完成
     * @throws IOException IO流错误
     */
    public boolean uploadFile(String fileName, InputStream is, String toRemotePath) throws IOException {
        if (ftpClient == null) {
            return false;
        }
        if (!ftpClient.isConnected()) {
            return false;
        }
        ftpClient.changeWorkingDirectory(toRemotePath);
        boolean bool = ftpClient.storeFile(changeFileNameCharset(fileName), is);
        is.close();
        return bool;
    }
    
    /**
     * 上传文件或目录
     *
     * @param file 上传的文件或目录
     * @param remotePath ftp远程目录
     * @throws IOException IO流错误
     */
    private void uploadFile(File file, String remotePath) throws IOException {
        if (file == null) {
            return;
        }
        if (ftpClient == null) {
            return;
        }
        if (!ftpClient.isConnected()) {
            return;
        }
        if (file.isDirectory()) {
            File[] subFiles = file.listFiles();
            if (subFiles == null || subFiles.length == 0) {
                return;
            }
            String path = remotePath + "//" + file.getName();
            //在FTP服务器上创建同名文件夹
            ftpClient.makeDirectory(path);
            for (File subFile : subFiles) {
                if (subFile.isDirectory()) {
                    //ftpClient.changeWorkingDirectory("//");
                    //ftpClient.makeDirectory(path + "//" + subFile.getName());
                    ftpClient.changeWorkingDirectory(path);
                    String subFileName = changeFileNameCharset(subFile.getName());
                    if (!ftpClient.changeWorkingDirectory(path + "/" + subFileName)) {
                        ftpClient.makeDirectory(subFileName);
                    }
                    uploadFile(subFile, path);
                } else if (subFile.isFile()) {
                    uploadFile(subFile.getName(), new FileInputStream(subFile), path + "//");
                }
            }
        } else if (file.isFile()) {
            uploadFile(file.getName(), new FileInputStream(file), remotePath);
        }
    }
    
    /**
     * 上传文件或文件目录
     *
     * @param file 上传的文件或目录
     * @param remotePath ftp远程目录
     * @throws IOException IO流错误
     */
    public void uploadDirectory(File file, String remotePath) throws IOException {
        uploadFile(file, remotePath);
    }
    
    /**
     * 下载单个文件
     *
     * @param remotePath ftp远程目录
     * @param fileName 下载的文件名
     * @param os 文件输出流
     * @return true正确下载完成
     */
    public boolean downloadFile(String remotePath, String fileName, OutputStream os) {
        boolean bool = false;
        try {
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (fileName.equals(ftpFile.getName())) {
                    ftpClient.retrieveFile(ftpFile.getName(), os);
                    os.flush();
                    os.close();
                }
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
            bool = false;
        }
        return bool;
    }
    
    /**
     * 下载整个目录,包括文件和子目录
     *
     * @param remotePath ftp远程目录
     * @param localPath 本地目录
     * @throws IOException IO流错误
     */
    public void downloadDirectory(String remotePath, String localPath) throws IOException {
        downloadDirectory(remotePath, new File(localPath + "//"));
    }
    
    /**
     * 下载整个目录,包括文件和子目录
     *
     * @param remotePath ftp远程目录
     * @param localDic 本地目录
     * @throws IOException IO流错误
     */
    public void downloadDirectory(String remotePath, File localDic) throws IOException {
        if (remotePath == null) {
            return;
        }
        if ("".equals(remotePath)) {
            return;
        }
        if (localDic == null) {
            return;
        }
        if (!localDic.exists()) {
            localDic.mkdirs();
        }
        FTPFile[] ftpFiles = ftpClient.listFiles(remotePath);
        if (ftpFiles == null) {
            return;
        }
        if (ftpFiles.length == 0) {
            return;
        }
        for (FTPFile ftpFile : ftpFiles) {
            String filePath = localDic.getAbsolutePath() + "//" + ftpFile.getName();
            if (ftpFile.isDirectory()) {
                downloadDirectory(remotePath + "//" + ftpFile.getName(), new File(filePath));
            } else {
                //downloadFile(remotePath, ftpFile.getName(), os);
                try (FileOutputStream os = new FileOutputStream(new File(filePath))) {
                    ftpClient.changeWorkingDirectory(remotePath);
                    ftpClient.retrieveFile(ftpFile.getName(), os);
                    os.flush();
                }
            }
        }
    }
    
    /**
     * 删除文件
     *
     * @param remotePath ftp远程目录
     * @param fileName 删除的文件名
     * @return true成功删除文件
     */
    public boolean deleteFile(String remotePath, String fileName) {
        boolean bool = false;
        try {
            ftpClient.changeWorkingDirectory(remotePath);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile ftpFile : ftpFiles) {
                if (fileName.equals(ftpFile.getName())) {
                    bool = ftpClient.deleteFile(fileName);
                    break;
                }
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
        return bool;
    }
    
    /**
     * 关闭FTP连接
     *
     * @return true关闭成功
     * @throws IOException IO流错误
     */
    public boolean close() throws IOException {
        if (ftpClient == null) {
            return true;
        }
        boolean bool = ftpClient.logout();
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }
        return bool;
    }
    

    }



    ######
    /**
         * 发送配置相关文件到cdn资源服务器上
         *
         * @param failCount 当前失败次数
         * @param maxFailCount 最大失败次数
         */
        private static void uploadFileToFtpServer(AtomicInteger failCount, final int maxFailCount) {
            FtpSession ftp = null;
            try {
                ftp = uploadFileToFtpServer();
            } catch (IOException e) {
                int count = failCount.incrementAndGet();
                if (count < maxFailCount) {
                    Config.uploadFileToFtpServer(failCount, maxFailCount);
                    logger.error("上传配置文件到FTP服务器失败,第" + count + "失败后再次传输,最大失败重传次数为:" + maxFailCount);
                }
            } finally {
                if (ftp != null) {
                    try {
                        ftp.close();
                    } catch (IOException ex) {
    
                    }
                }
            }
        }
    
        /**
         * 发送配置相关文件到cdn资源服务器上
         *
         * @return ftp访问连接会话
         * @throws IOException
         */
        private static FtpSession uploadFileToFtpServer() throws IOException {
            boolean cdn = false;
            String cdnDic = null;
            for (ServerInfo info : serversList) {
                String fileUrl = info.getFileUrl();
                if (fileUrl.contains(阿里云CDN源服务器(FTP服务器)Host地址)) {
                    cdn = true;
                    int idx = fileUrl.indexOf("//");
                    fileUrl = fileUrl.substring(idx + 2);
                    idx = fileUrl.indexOf("/");
                    cdnDic = fileUrl.substring(idx);
                    break;
                }
            }
            if (cdn) {
                logger.info("正在尝试将配置文件上传到FTP服务器……");
                FtpSession ftp = new FtpSession(CDN源服务器地址(FTP服务器), 51021, "p900_fpdlm", "BF22QGzqK6KRb2QU", null);
                File configDic = new File(usrConfigPath);
                if (configDic.exists() && configDic.isDirectory()) {
                    File[] subFiles = getUploadFileList(configDic);
                    if (cdnDic == null) {
                        cdnDic = "/usr.config";
                    }
                    ftp.changeWorkingDirectory(cdnDic);
                    int version = -1;
                    for (File file : subFiles) {
                        if (file.getName().equals("version.txt")) {
                            version = getConfigVersion(file);
                            break;
                        }
                    }
                    for (File file : subFiles) {
                        String fileName = file.getName();
                        if (version > 0) {
                            int idx = fileName.indexOf(".");
                            String name = fileName.substring(0, idx);
                            String suffix = fileName.substring(idx);
                            fileName = name + version + suffix;
                        }
                        ftp.uploadFile(fileName, new FileInputStream(file));
                        logger.info("上传文件 (" + fileName + ")到FTP服务器");
                    }
                }
                ftp.close();
                return ftp;
            }
            return null;
        }



    ######我先看看, 谢谢啊!######不用客气,都是苦逼程序员,理该互相帮助######
    2020-06-06 11:54:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载