java中使用FTP传送文件或者取得文件,可以使用Jakarta Commons NET(FTPClient)的包来实现。
具体的示例如下:(例子是从网上拷贝的)
package test.ftp;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpClientUtil {
private static final int FTP_PORT = 21;
public static void main(String[] args) {
try {
//读入文件
FileInputStream fis = new FileInputStream("c:\testftp.txt");
//传送文件到FTP服务器
FtpClientUtil.sendFile("localhost", FTP_PORT, "testuser", "testpassword", "remoteFilename", fis);
//从FTP服务器取得文件
FileOutputStream fos = new FileOutputStream("localfile");
FtpClientUtil.retrieveFile("localhost", FTP_PORT, "testuser", "testpassword", "remoteFilename", fos);
} catch (Exception e) {
e.printStackTrace();
}
}
//上传文件
public static void sendFile (String host,
int port,
String user,
String password,
String remoteFilename,
InputStream is
) throws Exception {
FTPClient ftpclient = new FTPClient();
try {
//设置服务器名和端口
ftpclient.connect(host, port);
int reply = ftpclient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
//连接错误的时候报错。
Exception ee = new Exception("Can't Connect to :" + host);
throw ee;
}
//登录
if (ftpclient.login(user, password) == false) {
// invalid user/password
Exception ee = new Exception("Invalid user/password");
throw ee;
}
//设置传送文件模式
ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
//传送文件
ftpclient.storeFile(remoteFilename, is);
} catch (IOException e) {
throw e;
} finally {
try {
ftpclient.disconnect(); //解除连接
} catch (IOException e) {
}
}
}
//文件下载
public static void retrieveFile(String host,
int port,
String user,
String password,
String remoteFilename,
OutputStream os) throws Exception {
FTPClient ftpclient = new FTPClient();
try {
//设置服务器名和端口
ftpclient.connect(host, port);
int reply = ftpclient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
//连接错误
Exception ee = new Exception("Can't Connect to :" + host);
throw ee;
}
//登录
if (ftpclient.login(user, password) == false) {
// invalid user/password
Exception ee = new Exception("Invalid user/password");
throw ee;
}
//设置传送模式
ftpclient.setFileType(FTP.BINARY_FILE_TYPE);
// 取得文件
ftpclient.retrieveFile(remoteFilename, os);
} catch (IOException e) {
throw e;
} finally {
try {
ftpclient.disconnect(); //解除连接
} catch (IOException e) {
}
}
}
}