2011-02-24

使用 Java 上載檔案至 FTP 伺服器 (Use Java to upload file to FTP Server)

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public static void send(String hostname, int port, String username, String password, File source, String destination) throws IOException {
    FtpClient ftp = new FtpClient(hostname, port);
    ftp.login(username, password);
    ftp.binary();
    FileInputStream fos = new FileInputStream(source);
    TelnetOutputStream tos = ftp.put(destination);
    DataOutputStream dos = new DataOutputStream(tos);
    byte[] buffer = new byte[1024 * 1024];
    for (int length; (length = fos.read(buffer)) > 0;) {
        dos.write(buffer, 0, length);
    }
    tos.flush();
    tos.close();
    fos.close();
}

public static void send(String hostname, String username, String password, File source, String destination) throws IOException {
    send(hostname, 21, username, password, source, destination);
}

沒有留言 :

張貼留言