这是一个简单的FTP实现类,功能较少,请大家一起完善一下

bo-boom 2008-08-22 02:38:08
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();

}

}

...全文
89 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,538

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧