今天整理了一个JAVA下的FTP类,希望对大家有所帮助
/*
*@anthor 闫世新 Dec 31, 2008
*
*用能描述:
*/
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpLoginException;
public class FTP {
// private static Log log = LogFactory.getLog(FTP.class);
private String a;
private static FtpClient ftpClient;
private TelnetOutputStream outs;
private DataOutputStream outputs;
private TelnetInputStream ins;
private int ch;
private static FTP ftp = null;
// 上传主机:boss主机
private String _host;
public String getHost()
{
return this._host;
}
public void SetHost(String value)
{
this._host = value;
}
// 上传主机:boss主机
private int _port;
public int getPort()
{
return this._port;
}
public void setPort(int value)
{
this._port = value;
}
// ftp账号
private String _username;
public String getUserName()
{
return this._username;
}
public void setUserName(String value)
{
this._username = value;
}
// ftp密码
private String _password;
public String getPassword()
{
return this._password;
}
public void setPassword(String value)
{
this._password = value;
}
HashMap map = new HashMap();
static {
ftp = new FTP();
}
public static FTP newInstance() {
if (ftp == null)
ftp = new FTP();
return ftp;
}
/**
*
*/
public FTP() {
// TODO Auto-generated constructor stub
}
// public static void main(String[] args) {
// String hostname = "xx.xx.xx.xx";
// int port = 21;
// String uid = "user";
// String pwd = "user";
//
// // 连接ftp服务器
// FTP ft = new FTP();
// ft.connect(hostname, uid, pwd);
// // ft.list();
// ft.uploadFile("ups", "c://output.log");
// ft.uploadFile("ups/1", "c://声卡驱动程序.exe");
// // ft.deleFile("ups");
//
// }
public FtpClient connect()
{
//log.debug("正在连接" + hostname + ",请等待.....");
System.out.println("正在连接" + this._host + ",请等待.....");
try {
// ftpClient = new FtpClient(hostname, port);
ftpClient = new FtpClient(this._host,this._port);
// log.debug(ftpClient.getResponseString());
ftpClient.login(this._username, this._password);
// log.debug(ftpClient.getResponseString());
ftpClient.binary();
// log.debug(ftpClient.getResponseString());
// aftp.openPortDataConnection();
a = "连接主机:" + this._host + "成功!";
// log.debug(a);
System.out.println(a);
} catch (FtpLoginException e) {
a = "登陆主机:" + this._host + "失败!请检查用户名或密码是否正确:" + e;
// log.debug(a);
System.out.println(a);
// return false;
} catch (IOException e) {
a = "连接主机:" + this._host + "失败!请检查主机名和端口是否正确:" + e;
//log.debug(a);
System.out.println(a);
// return false;
} catch (SecurityException e) {
a = "无权限与主机:" + this._host + "连接!请检查是否有访问权限:" + e;
// log.debug(a);
System.out.println(a);
// return false;
}
// log(RWFileDir,a);
return ftpClient;
}
public boolean uploadFile(String path, String filepathname) {
boolean iscd = false;
int cdnum = 0;
// 进入到path指定的目录下
if (path.trim().length() != 0 && path!= null)
try {
iscd = true;
String[] paths = path.split("/");
int j = 0;
for (int i = 0; i < (j = paths.length); i++) {
ftpClient.cd(paths[i]);
++cdnum;
// log.debug("cdnum = "+ cdnum );
}
ftpClient.binary();
} catch (IOException e1) {
// TODO Auto-generated catch block
// log.debug("FTP服务器目录[/" + path + "]不存在或无法访问!");
System.out.println("FTP服务器目录[/" + path + "]不存在或无法访问!");
// 回到根目录
if (iscd) {
for (int i = 0; i < cdnum; i++) {
try {
ftpClient.cdUp();
// log.debug("cdUp["+( i+1) +"]");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ftpClient.binary();
}
return false;
}
boolean result = true;
String message = "";
if (ftpClient != null) {
// log.debug("正在上传文件" + filepathname + ",请等待....");
System.out.println("正在上传文件" + filepathname + ",请等待....");
try {
String filename = filepathname.substring(filepathname
.lastIndexOf("//") + 1);
// 如果文件存在则不上传
if (isExist(filename)) {
// log.debug("同名文件[" + filename + "]已经存在,不能上传!");
System.out.println("同名文件[" + filename + "]已经存在,不能上传!");
return false;
}
TelnetOutputStream os = ftpClient.put(filename.concat(".temp"));
BufferedInputStream bin = new BufferedInputStream(
new FileInputStream(filepathname));
byte[] bytes = new byte[1024];
int c;
while ((c = bin.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
os.close();
bin.close();
//log.debug("上传文件完成。");
rename(filename.concat(".temp"), filename);
message = "上传" + filepathname + "文件成功!";
//log.debug(message);
System.out.println(message);
} catch (IOException e) {
message = "上传" + filepathname + "文件失败!" + e;
//log.debug(message);
System.out.println(message);
// log(RWFileDir,message);
result = false;
} finally {
// 如果此时不在根目录下,则返回到根目录
if (iscd) {
for (int i = 0; i < cdnum; i++) {
try {
ftpClient.cdUp();
// log.debug("cdUp["+( i+1) +"]");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ftpClient.binary();
}
}
} else {
result = false;
}
return result;
}
public boolean downloadFile(String RWFileDir, String filepathname) {
boolean result = true;
String message = "";
if (ftpClient != null) {
//log.debug("正在下载文件" + filepathname + ",请等待....");
String badfile = filepathname.substring(filepathname.length() - 4,
filepathname.length());
String badlog = filepathname.substring(filepathname.length() - 7,
filepathname.length());
String baddir = "";
if ((badfile.compareTo(".bad") != 0)
&& (badlog.compareTo(".badlog") != 0)) {
baddir = "subunsubtosp//";
} else {
baddir = "bad//";
}
String strdir = "subunsubtosp//";
String fileName =filepathname.substring(filepathname.lastIndexOf("/")+1);
String dir =filepathname.substring(1,filepathname.lastIndexOf("/"));
// log.debug("file DIR is :"+dir +" and fileName is :"+fileName );
// log.debug(RWFileDir + baddir + filepathname);
try {
// FtpClient fc=new FtpClient("192.168.0.56",2121);
// fc.login("lee","lee");
int ch;
// File fi = new File(RWFileDir + baddir + filepathname);
File dirs = new File(RWFileDir+dir);
if(!dirs.exists())dirs.mkdirs();
// log.debug("new file dir is : "+RWFileDir+dir+"/"+fileName);
File fi = new File(RWFileDir+dir, fileName);
// log.debug(fi.getAbsolutePath());
// aftp.cd(strdir);
RandomAccessFile getFile = new RandomAccessFile(fi, "rw");
getFile.seek(0);
TelnetInputStream fget = ftpClient.get(filepathname);
DataInputStream puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
// s.delete();
fget.close();
getFile.close();
// fc.closeServer();
message = "下载" + filepathname + "文件到" + RWFileDir +dir + "目录成功!";
//log.debug(message);
// log(RWFileDir,message);
} catch (IOException e) {
message = "下载" + filepathname + "文件到" + RWFileDir +dir + "目录失败!" + e;
// log.debug(message);
// log(RWFileDir,message);
result = false;
}
} else {
result = false;
}
return result;
}
public void rename(String oldName, String newName) {
try {
ftpClient.rename(oldName, newName);
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// log.debug("rename ["+oldName+"] to ["+newName+"] failure.");
return;
}
// log.debug("rename ["+oldName+"] to ["+newName+"] successful.");
}
public void deleFile(String RWFileDir) {
// try {
// 取得ReadFile目录下的txt文件
String sdir = RWFileDir;
File fdir = new File(sdir);
String FileName = "";
int j = fdir.list().length;
//log.debug(sdir + "目录下要删除的文件数:" + fdir.list().length);
File file;
for (int i = 0; i < j; i++) {
// 删除subunsubfromsp中的txt文件
FileName = RWFileDir + "subunsubfromsp//" + (fdir.list())[0];
file = new File(FileName);
file.delete();
// log.debug("已经成功删除" + FileName + "文件!");
}
}
public void stop() {
String message = "";
try {
if (ftpClient != null) {
ftpClient.closeServer();
message = "与主机" + this._host + "连接已断开!";
System.out.println(message);
// log.debug(message);
// log(RWFileDir,message);
}
} catch (IOException e) {
message = "与主机" + this._host + "断开连接失败!" + e;
// log.debug(message);
// log(RWFileDir,message);
}
}
public HashMap list() {
map.clear();
try {
TelnetInputStream in = ftpClient.list();
byte[] bt = new byte[in.available()];
in.read(bt);
String str = new String(bt);
if (str.trim().equals(""))
return null;
String tmp[] = str.split("/r/n");
for (int i = 0; i < tmp.length; i++) {
// if(tmp[i].startsWith("d"))
map.put(tmp[i].substring(tmp[i].lastIndexOf(" ") + 1), tmp[i]
.substring(0, 4));
// /log.debug("目录["+tmp[i].substring(tmp[i].lastIndexOf("
// ")+1)+"]");
// else
// log.debug("文件["+tmp[i].substring(tmp[i].lastIndexOf("
// ")+1)+"]");
}
// System.out.println( str );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return map;
}
public boolean isExist(String filename) {
if (list() == null)
return false;
if (list().get(filename) == null)
return false;
else
return true;
}
}