Jakarta Commons NET(FTPClient)の簡単な例
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) {
}
}
}
}