这是一个简单的FTP实现类,功能较少,请大家一起完善一下
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
public class Ftp {
private FtpClient ftpClient;
/**
* 连接FTP服务器
*
* @param server FTP服务器IP地址
* @param user 登录名
* @param password 密码
* @throws IOException
*/
public void connectServer(String server, String user, String password)
throws IOException {
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
ftpClient.binary();
}
/**
* 连接FTP服务器,并指定登录路径
*
* @param server FTP服务器IP地址
* @param user 登录名
* @param password 密码
* @param path 登录路径
* @throws IOException
*/
public void connectServer(String server, String user, String password,
String path) throws IOException {
ftpClient = new FtpClient();
ftpClient.openServer(server);
ftpClient.login(user, password);
ftpClient.cd(path);
ftpClient.binary();
}
/**
* 上传文件.上传成功返回1,上传失败返回0.
*
* @param iniputStream 上传文件的输入流
* @param newName 上传文件后对文件的重命名
* @return int
* @throws IOException
*/
public int upload(InputStream in, String newName) throws IOException {
TelnetOutputStream os = null;
try {
// 命名文件
os = ftpClient.put(newName);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} catch (IOException e) {
return 0;
} finally {
if (in != null) {
in.close();
}
if (os != null) {
os.close();
}
}
return 1;
}
/**
* 获得文件和目录列表
*
* @return
* @throws IOException
*/
public List getFileList() throws IOException {
List list = new ArrayList();
TelnetInputStream in = ftpClient.nameList(".");
BufferedReader bf = new BufferedReader(new InputStreamReader(in));
String l = null;
while ((l = bf.readLine()) != null) {
if (!l.equals(".") && !l.equals(".."))
list.add(l);
}
return list;
}
/**
* 下载文件
*
* @param fileName
* @return
* @throws IOException
*/
public InputStream getFile(String fileName) throws IOException {
TelnetInputStream in = null;
in = ftpClient.get(fileName);
return in;
}
/**
* 转到指定目录
*
* @param path
* @throws IOException
*/
public void cdPath(String path) throws IOException {
ftpClient.cd(path);
}
/**
* 关闭FTP服务
*
* @throws IOException
*/
public void closeFTPClient() throws IOException {
if (ftpClient != null)
ftpClient.closeServer();
}
}