• 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;
    }
  • 相关阅读:
    网文阅读笔记
    UUID
    各种网站
    项目
    常用正则表达式
    Struts 2.0 HelloWorld
    接口与抽象类(深入多态)
    #define的优点/volatile的好处
    基本套接口编程
    大小端判断及相互转化
  • 原文地址:https://www.cnblogs.com/crane13/p/3150115.html
Copyright © 2020-2023  润新知