zoukankan      html  css  js  c++  java
  • java上传文件到FTP服务器

     在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件、下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件。


    public static String ftpUpload(String url, String port, String username,
    String password, String remotePath, String fileNamePath,
    String fileName) {
    FTPClient ftpClient = new FTPClient();
    FileInputStream fis = null;
    String returnMessage = "0";
    try {
    ftpClient.connect(url, Integer.parseInt(port));
    boolean loginResult = ftpClient.login(username, password);
    int returnCode = ftpClient.getReplyCode();
    if (loginResult && FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
    ftpClient.makeDirectory(remotePath);
    // 设置上传目录
    ftpClient.changeWorkingDirectory(remotePath);
    ftpClient.setBufferSize(1024);
    ftpClient.setControlEncoding("UTF-8");
    ftpClient.enterLocalPassiveMode();
    fis = new FileInputStream(fileNamePath + fileName);
    ftpClient.storeFile(fileName, fis);
     
    returnMessage = "1"; // 上传成功
    } else {// 如果登录失败
    returnMessage = "0";
    }
     
    } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException("FTP客户端出错!", e);
    } finally {
    // IOUtils.closeQuietly(fis);
    try {
    ftpClient.disconnect();
    } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException("关闭FTP连接发生异常!", e);
    }
    }
    return returnMessage;
    }
  • 相关阅读:
    计算机思维
    easyui增删改查前段代码
    文本相似度分析
    布隆过滤器
    SQL Server事务
    堆排序(Heapsort)
    游标
    存储过程
    触发器
    Thread部分总结以及小例子
  • 原文地址:https://www.cnblogs.com/crane13/p/3150115.html
Copyright © 2011-2022 走看看