JAVA中实现FTP功能代码

2008-10-27 14:27:52 来源:不详 作者:佚名 点击:
JAVA中实现FTP功能代码



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;

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

public final class FtpTest {

public static final void main(String[] args) {
int base = 0;
boolean storeFile = false, binaryTransfer = false, error = false;
String server, username, password, remote, local;
FTPClient ftp;
server = "172.16.1.1";
username = "public";
password = "public";
remote = "ht/isic-0.05.tar";
local = "d:\\isic-0.05.tar";

ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out)));
//----------------新添加的----------------
FTPClient ftest = new FTPClient();
try {
ftest.connect(server);
ftest.login(username, password);
FTPFile[] files = ftest.listFiles();
System.out.println("输出ftp服务器上根目录下的文件或文件夹名字开始:\n");
for (int i = 0; i < files.length; i++) {
System.out.println(IsoToCh(files[i].getName()));
}
System.out.println("输出ftp服务器上根目录下的文件或文件夹名字结束。\n");
} catch (SocketException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
}
//---------------------------------------------------

try {
int reply;
ftp.connect(server);
System.out.println("Connected to " + server + ".");

// 尝试连接后,需要检验返回代码以验证是否连接成功
reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP server refused connection.");
System.exit(1);
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException f) {
// do nothing
}
}
System.err.println("Could not connect to server.");
e.printStackTrace();
System.exit(1);
}

__main: try {
if (!ftp.login(username, password)) {
ftp.logout();
error = true;
break __main;
}

System.out.println("Remote system is " + ftp.getSystemName());

if (binaryTransfer)
ftp.setFileType(FTP.BINARY_FILE_TYPE);

// 默认状态下使用passive mode因为大多都在防火墙后面
ftp.enterLocalPassiveMode();

if (storeFile) {
InputStream input;
input = new FileInputStream(local);
ftp.storeFile(remote, input);
input.close();
} else {
OutputStream output;
output = new FileOutputStream(local);
ftp.retrieveFile(remote, output);
output.close();
}
ftp.logout();
} catch (FTPConnectionClosedException e) {
error = true;
System.err.println("Server closed connection.");
e.printStackTrace();
} catch (IOException
9 7 3 1 2 4 8 :



本类最新行业评测技巧教程学院
本类热点本日本周本月
本类推荐本日本周本月

广告联系 | 版权说明 | 意见建议 | 加入收藏 | 军网站群 [ 军软件园 - 军软件商城 - 军软件园论坛 ]

电信与信息服务业务经营许可证:京ICP证050203