日期:2014-05-20  浏览次数:20819 次

如何让Java把本地的文件ftp到另外一台服务器上?
各位大虾:
        机器A上有一目录,如/home/myfile,之下有一些文件,我想把这些文件通过java编写的程序ftp到机器B上。可以吗?能否给点思路?

        谢谢先

------解决方案--------------------
用 sun.net.ftp.FtpClient 。
FtpClient ftp = new FtpClient();
ftp.openServer(Address,Port));
ftp.login(User,Password);

ftp.cd(FTPDirectory);
ftp.put(FTPFileName);
得到一个文件流
就可以传文件了。
------解决方案--------------------
下面是我寫過關於FTPClient,看對你有沒有一點幫助

package com.XXXX;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;

public class myFtpClient {
protected FTPClient FTP_;
protected String host;
protected int port = 21;
protected String userID;
protected String password;

public myFtpClient() {
FTP_ = new FTPClient();
}

public myFtpClient(String host, String userID, String password) {
this.host = host;
this.userID = userID;
this.password = password;
FTP_ = new FTPClient();
}

public myFtpClient(String host, int port, String userID, String password) {
this.host = host;
this.port = port;
this.userID = userID;
this.password = password;
FTP_ = new FTPClient();
}

/**
* set Info
*
* @param host
* @param port
* @param userID
* @param password
*/
public void setInfo(String host, int port, String userID, String password) {
this.host = host;
this.port = port;
this.userID = userID;
this.password = password;
}

/**
* open connection
*
* @return boolean
* @throws java.io.IOException
* @throws SocketException
*/
public boolean connect() throws Exception {
FTP_.setDefaultPort(this.port);
FTP_.setDataTimeout(120000); //timeout為120秒
FTP_.connect(this.host);
if (!FTP_.isConnected()) {
throw new Exception( "NOT CONNECT FTP ");
}
if (!FTPReply.isPositiveCompletion(FTP_.getReplyCode())) {
FTP_.disconnect();
System.out.println( "Connection refused. ");
return false;
}
if (FTP_.login(this.userID, this.password)) {
return true;
} else {
throw new Exception( "NOT LOGIN ");
}
}

/**
* open connection by info
*
* @param host
* @param userID
* @param password
* @return boolean
* @throws IOException
* @throws SocketException
*/
public boolean connect(String host, String userID, String password)
throws IOException, SocketException {
try {
FTP_.connect(host);
if (!FTPReply.isPositiveCompletion(FTP_.getReplyCode())) {
FTP_.disconnect();
System.out.println( "Connection refused. ");
return false;
}
FTP_.login(userID, password);
return true;
} catch (SocketException e) {
throw e;
} catch (IOException e) {
throw e;
}
}

------解决方案--------------------
楼上好强
------解决方案--------------------