如何将文件上传到 FTP 服务器? [英] How do you upload a file to an FTP server?

查看:48
本文介绍了如何将文件上传到 FTP 服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I created a function to download files from an FTP server that I have access to. How would I upload files back to the FTP server?

以下是我使用的 download_files 方法:

Below is the download_files method i used:

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 库.

Use the FTPClient Class from the Apache Commons Net library.

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

This is a snippet with an example:

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

这篇关于如何将文件上传到 FTP 服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆