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;
    }
  • 相关阅读:
    H3C日志文件读取
    sql2000 转sql2008
    常用sql大全
    安装linux后,重新装windows,修复mbr引导
    SQL Server推荐使用 SET 而不是 SELECT 对变量进行赋值
    ORCLE 截取固定字符
    又是一个无聊的周未
    转一个无聊的爱情故事:如果有个女生为你哭
    Windows Mobile 6 SDK
    扩展FCKeditor
  • 原文地址:https://www.cnblogs.com/crane13/p/3150115.html
Copyright © 2011-2022 走看看