java - 如何将文件上传到 FTP 服务器?

标签 java upload ftp download

我创建了一个从我有权访问的 FTP 服务器下载文件的函数。如何将文件上传回 FTP 服务器?

下面是我使用的 download_files 方法:

public static void download_files(String un, String pw, String ip, String dir, String fn, String fp){

    URLConnection con;
    BufferedInputStream in = null;
    FileOutputStream out = null;

    try{
        URL url = new URL("ftp://"+un+":"+pw+"@"+ip+"/"+dir+"/"+fn+";type=i");
        con = url.openConnection();
        in = new BufferedInputStream(con.getInputStream());
        out = new FileOutputStream(fp+fn);

        int i = 0;
        byte[] bytesIn = new byte[1024];

        while ((i = in.read(bytesIn)) >= 0) {
            out.write(bytesIn, 0, i);
        }

    }catch(Exception e){
        System.out.print(e);
        e.printStackTrace();
        System.out.println("Error while FTP'ing "+fn);
    }finally{
        try{
            out.close();
            in.close();
        }catch(IOException e){
            e.printStackTrace();
            System.out.println("Error while closing FTP connection");
        }
    }
}

最佳答案

使用FTPClient类来自Apache Commons Net图书馆。

这是一个带有示例的片段:

FTPClient client = new FTPClient();
FileInputStream fis = null;

try {
    client.connect("ftp.domain.com");
    client.login("admin", "secret");

    //
    // Create an InputStream of the file to be uploaded
    //
    String filename = "Touch.dat";
    fis = new FileInputStream(filename);

    //
    // Store file to server
    //
    client.storeFile(filename, fis);
    client.logout();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fis != null) {
            fis.close();
        }
        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

摘自http://www.kodejava.org/examples/356.html的片段

关于java - 如何将文件上传到 FTP 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58639148/

相关文章:

bash - 可以通过没有 aws-cli 的 shell 脚本上传到 S3 吗?

java - 上传图片时出现OutOfMemory异常如何解决?

java - 如何获取任何应用程序上下文根的文件系统路径

java - VisualVM - "Used heap"中包含什么?

java - 想要使用预先签名的 url 将文件上传到 s3 存储桶

Angular 上传进度未正确报告

python - 带 FTP 的虚拟文件系统

python - 如何在 FTP 连接中后退 : PYTHON

iis - 被动 FTP 而不是主动 FTP

java - 如何将两个不同大小的矩阵相乘