网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

关于javaftp代码示列的信息

怎么用Java实现FTP上传

sun.net..,该类库主要提供了用于建立FTP连接的类。利用这些类的方法,编程人员可以远程登录到FTP服务器,列举该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵盖了几乎所有FTP的功能,FtpClient的实例变量保存了有关建立"代理"的各种信息。下面给出了这些实例变量:

成都创新互联-专业网站定制、快速模板网站建设、高性价比长顺网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式长顺网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖长顺地区。费用合理售后完善,十年实体公司更值得信赖。

public static boolean useFtpProxy

这个变量用于表明FTP传输过程中是否使用了一个代理,因此,它实际上是一个标记,此标记若为TRUE,表明使用了一个代理主机。

public static String ftpProxyHost

此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机名。

public static int ftpProxyPort此变量只有在变量useFtpProxy为TRUE时才有效,用于保存代理主机的端口地址。

FtpClient有三种不同形式的构造函数,如下所示:

1、public FtpClient(String hostname,int port)

 此构造函数利用给出的主机名和端口号建立一条FTP连接。

2、public FtpClient(String hostname)

此构造函数利用给出的主机名建立一条FTP连接,使用默认端口号。

3、FtpClient()

此构造函数将创建一FtpClient类,但不建立FTP连接。这时,FTP连接可以用openServer方法建立。

一旦建立了类FtpClient,就可以用这个类的方法来打开与FTP服务器的连接。类ftpClient提供了如下两个可用于打开与FTP服务器之间的连接的方法。

public void openServer(String hostname)

这个方法用于建立一条与指定主机上的FTP服务器的连接,使用默认端口号。

public void openServer(String host,int port)

这个方法用于建立一条与指定主机、指定端口上的FTP服务器的连接。

打开连接之后,接下来的工作是注册到FTP服务器。这时需要利用下面的方法。

public void login(String username,String password)

此方法利用参数username和password登录到FTP服务器。使用过Intemet的用户应该知道,匿名FTP服务器的登录用户名为anonymous,密码一般用自己的电子邮件地址。

下面是FtpClient类所提供的一些控制命令。

public void cd(String remoteDirectory):该命令用于把远程系统上的目录切换到参数remoteDirectory所指定的目录。

public void cdUp():该命令用于把远程系统上的目录切换到上一级目录。

public String pwd():该命令可显示远程系统上的目录状态。

public void binary():该命令可把传输格式设置为二进制格式。

public void ascii():该命令可把传输协议设置为ASCII码格式。

public void rename(String string,String string1):该命令可对远程系统上的目录或者文件进行重命名操作。

除了上述方法外,类FtpClient还提供了可用于传递并检索目录清单和文件的若干方法。这些方法返回的是可供读或写的输入、输出流。下面是其中一些主要的方法。

public TelnetInputStream list()

返回与远程机器上当前目录相对应的输入流。

public TelnetInputStream get(String filename)

获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。

public TelnetOutputStream put(String filename)

以写方式打开一输出流,通过这一输出流把文件filename传送到远程计算机

package myUtil;

import java.io.DataInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.ArrayList;

import java.util.List;

import java.util.StringTokenizer;

import sun.net.TelnetInputStream;

import sun.net.TelnetOutputStream;

import sun.net.;

/**

* ftp上传,下载

*

* @author why 2009-07-30

*

*/

public class FtpUtil {

private String ip = "";

private String username = "";

private String password = "";

private int port = -1;

private String path = "";

FtpClient ftpClient = null;

OutputStream os = null;

FileInputStream is = null;

public FtpUtil(String serverIP, String username, String password) {

this.ip = serverIP;

this.username = username;

this.password = password;

}

public FtpUtil(String serverIP, int port, String username, String password) {

this.ip = serverIP;

this.username = username;

this.password = password;

this.port = port;

}

/**

* 连接ftp服务器

*

* @throws IOException

*/

public boolean connectServer() {

ftpClient = new FtpClient();

try {

if (this.port != -1) {

ftpClient.openServer(this.ip, this.port);

} else {

ftpClient.openServer(this.ip);

}

ftpClient.login(this.username, this.password);

if (this.path.length() != 0) {

ftpClient.cd(this.path);// path是ftp服务下主目录的子目录

}

ftpClient.binary();// 用2进制上传、下载

System.out.println("已登录到\"" + ftpClient.pwd() + "\"目录");

return true;

} catch (IOException e) {

e.printStackTrace();

return false;

}

}

/**

* 断开与ftp服务器连接

*

* @throws IOException

*/

public boolean closeServer() {

try {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

if (ftpClient != null) {

ftpClient.closeServer();

}

System.out.println("已从服务器断开");

return true;

} catch (IOException e) {

e.printStackTrace();

return false;

}

}

/**

* 检查文件夹在当前目录下是否存在

*

* @param dir

*@return

*/

private boolean isDirExist(String dir) {

String pwd = "";

try {

pwd = ftpClient.pwd();

ftpClient.cd(dir);

ftpClient.cd(pwd);

} catch (Exception e) {

return false;

}

return true;

}

/**

* 在当前目录下创建文件夹

*

* @param dir

* @return

* @throws Exception

*/

private boolean createDir(String dir) {

try {

ftpClient.ascii();

StringTokenizer s = new StringTokenizer(dir, "/"); // sign

s.countTokens();

String pathName = ftpClient.pwd();

while (s.hasMoreElements()) {

pathName = pathName + "/" + (String) s.nextElement();

try {

ftpClient.sendServer("MKD " + pathName + "\r\n");

} catch (Exception e) {

e = null;

return false;

}

ftpClient.readServerResponse();

}

ftpClient.binary();

return true;

} catch (IOException e1) {

e1.printStackTrace();

return false;

}

}

/**

* ftp上传 如果服务器段已存在名为filename的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

* @param filename

* 要上传的文件(或文件夹)名

* @return

* @throws Exception

*/

public boolean upload(String filename) {

String newname = "";

if (filename.indexOf("/") -1) {

newname = filename.substring(filename.lastIndexOf("/") + 1);

} else {

newname = filename;

}

return upload(filename, newname);

}

/**

* ftp上传 如果服务器段已存在名为newName的文件夹,该文件夹中与要上传的文件夹中同名的文件将被替换

*

* @param fileName

* 要上传的文件(或文件夹)名

* @param newName

* 服务器段要生成的文件(或文件夹)名

* @return

*/

public boolean upload(String fileName, String newName) {

try {

String savefilename = new String(fileName.getBytes("GBK"),

"GBK");

File file_in = new File(savefilename);// 打开本地待长传的文件

if (!file_in.exists()) {

throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");

}

if (file_in.isDirectory()) {

upload(file_in.getPath(), newName, ftpClient.pwd());

} else {

uploadFile(file_in.getPath(), newName);

}

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

return true;

} catch (Exception e) {

e.printStackTrace();

System.err.println("Exception e in Ftp upload(): " + e.toString());

return false;

} finally {

try {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 真正用于上传的方法

*

* @param fileName

* @param newName

* @param path

* @throws Exception

*/

private void upload(String fileName, String newName, String path)

throws Exception {

String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");

File file_in = new File(savefilename);// 打开本地待长传的文件

if (!file_in.exists()) {

throw new Exception("此文件或文件夹[" + file_in.getName() + "]有误或不存在!");

}

if (file_in.isDirectory()) {

if (!isDirExist(newName)) {

createDir(newName);

}

ftpClient.cd(newName);

File sourceFile[] = file_in.listFiles();

for (int i = 0; i sourceFile.length; i++) {

if (!sourceFile[i].exists()) {

continue;

}

if (sourceFile[i].isDirectory()) {

this.upload(sourceFile[i].getPath(), sourceFile[i]

.getName(), path + "/" + newName);

} else {

this.uploadFile(sourceFile[i].getPath(), sourceFile[i]

.getName());

}

}

} else {

uploadFile(file_in.getPath(), newName);

}

ftpClient.cd(path);

}

/**

* upload 上传文件

*

* @param filename

* 要上传的文件名

* @param newname

* 上传后的新文件名

* @return -1 文件不存在 =0 成功上传,返回文件的大小

* @throws Exception

*/

public long uploadFile(String filename, String newname) throws Exception {

long result = 0;

TelnetOutputStream os = null;

FileInputStream is = null;

try {

java.io.File file_in = new java.io.File(filename);

if (!file_in.exists())

return -1;

os = ftpClient.put(newname);

result = file_in.length();

is = new FileInputStream(file_in);

byte[] bytes = new byte[1024];

int c;

while ((c = is.read(bytes)) != -1) {

os.write(bytes, 0, c);

}

} finally {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

}

return result;

}

/**

* 从ftp下载文件到本地

*

* @param filename

* 服务器上的文件名

* @param newfilename

* 本地生成的文件名

* @return

* @throws Exception

*/

public long downloadFile(String filename, String newfilename) {

long result = 0;

TelnetInputStream is = null;

FileOutputStream os = null;

try {

is = ftpClient.get(filename);

java.io.File outfile = new java.io.File(newfilename);

os = new FileOutputStream(outfile);

byte[] bytes = new byte[1024];

int c;

while ((c = is.read(bytes)) != -1) {

os.write(bytes, 0, c);

result = result + c;

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return result;

}

/**

* 取得相对于当前连接目录的某个目录下所有文件列表

*

* @param path

* @return

*/

public List getFileList(String path) {

List list = new ArrayList();

DataInputStream dis;

try {

dis = new DataInputStream(ftpClient.nameList(this.path + path));

String filename = "";

while ((filename = dis.readLine()) != null) {

list.add(filename);

}

} catch (IOException e) {

e.printStackTrace();

}

return list;

}

public static void main(String[] args) {

FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");

;

boolean result = ("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");

System.out.println(result ? "上传成功!" : "上传失败!");

;

/**

* FTP远程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR

* REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU

* AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR

* NLST MKD XPWD MDTM PROT

* 在服务器上执行命令,如果用sendServer来执行远程命令(不能执行本地FTP命令)的话,所有FTP命令都要加上\r\n

* ftpclient.sendServer("XMKD /test/bb\r\n"); //执行服务器上的FTP命令

* ftpclient.readServerResponse一定要在sendServer后调用

* nameList("/test")获取指目录下的文件列表 XMKD建立目录,当目录存在的情况下再次创建目录时报错 XRMD删除目录

* DELE删除文件

*/

}

}

如何用JAVA实现FTP访问

在主函数中,完成服务器端口的侦听和服务线程的创建。我们利用一个静态字符串变量initDir 来保存服务器线程运行时所在的工作目录。服务器的初始工作目录是由程序运行时用户输入的,缺省为C盘的根目录。

具体的代码如下:

public class ftpServer extends Thread{

private Socket socketClient;

private int counter;

private static String initDir;

public static void main(String[] args){

if(args.length != 0) {

initDir = args[0];

}else{ initDir = "c:";}

int i = 1;

try{

System.out.println("ftp server started!");

//监听21号端口

ServerSocket s = new ServerSocket(21);

for(;;){

//接受客户端请求

Socket incoming = s.accept();

//创建服务线程

new ftpServer(incoming,i).start();

i++;

}

}catch(Exception e){}

}

java中怎么实现ftp服务器

学习了计算机网络之后,利用java写了一个ftp服务器。

一、实现的ftp命令

实现了基本的user,pass,list,port,quit,retr,cwd,stor等命令

二、以上命令所对应的功能

对应的功能是:下载,上传,获取服务器目录,切换目录等

三、用于测试的ftp客户端:windows自带的ftp客户端

四、实现的思想

1、使用ServerSocket进行监听,每个控制连接的请求到来之后,开启一个线程进行处理(这里使用的java bio,效率较差,对于控制连接最好使用NIO处理,之后会再写个

nio的实现)

2、 对于命令使用工厂方法模式进行设计,当需要添加新的命令的时候,只需要添加一个新的命令类,实现相应接口,修改工厂产生逻辑,而不用修改其他的程序代码。可

扩展性较好,同时符合开闭原则。

五、实现过程中碰到的问题

1、对于tcp与socket的关系理解错误,以为所有的数据的输入都是要经过serverSocket().accept()方法。其实,ServerSocket.accept()所对应的是tcp里面的三次握手建

立连接的阶段,之后的tcp的连接由客户端和服务器端的一对socket来维护,是属于establish阶段,在这个阶段,通信是全双工的,任何一方都能够发送数据。

socket.close()对应的阶段是断开连接(四次挥手)的阶段。

2、刚开始对于ftp协议不是很理解,不知道他的工作方式是怎样的,后来在看了tcp协议卷里面的ftp的内容之后,才知道ftp命令和应答码是关键。eg:刚开始测试时,在

输入用户名之后,不会提示输入密码的。原因:没有返回对应的应答码:331. 另外要注意的是:返回的数据要以换行回车作为结束--\r\n.

六、代码列表

简单说明:

ftpServer:是服务器的主程序,入口,同时负责监听本地的21号端口。

ControllerThread.java:用于处理控制连接的线程(每一个控制连接请求对应一个线程)ps:实在很浪费(流量小,连接多)。

Share:一些全局性数据的维护。

Command:是命令接口,定义了一个所有命令都要实现的方法。

CommandFactory:命令工厂,通过传人的参数,决定生成的命令对象。

UserCommand,PortCommand等:是具体ftp命令的实现

java ftp

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.UnsupportedEncodingException;

import sun.net.;

/**

*

* @author chenc

* @version 1.0

*

* 2008-02-19

*

*/

public class Ftp {

private String ip = "";

private String username = "";

private String password = "";

private String ftpDir = "";

private String localFileFullName = "";// 待上传的文件全名

private String ftpFileName = ""; // 文件上传到FTP后的名称

FtpClient ftpClient = null;

OutputStream os = null;

FileInputStream is = null;

public Ftp(String serverIP, String username, String password, String ftpDir) {

this.ip = serverIP;

this.username = username;

this.password = password;

if (ftpDir == null) {

this.ftpDir = "/ftpfileload";

} else {

try {

this.ftpDir = "/"

+ new String(ftpDir.getBytes("ISO-8859-1"), "GBK")

.toString();

} catch (UnsupportedEncodingException e) {

// TODO 自动生成 catch 块

e.printStackTrace();

}

}

}

private void createDir(String dir, FtpClient ftpClient) {

System.out.println(this.ftpDir);

ftpClient.sendServer("MKD " + dir + "\r\n");

try {

ftpClient.readServerResponse();

} catch (IOException e) {

// TODO 自动生成 catch 块

e.printStackTrace();

}

}

private Boolean isDirExist(String dir, FtpClient ftpClient) {

try {

ftpClient.cd(dir);

} catch (Exception e) {

// TODO 自动生成 catch 块

return false;

}

return true;

}

public String upload(String localFileFullName) {

// this.ftpFileName = "aaa.test";

// 获取文件后缀名

String ext = localFileFullName.substring(localFileFullName

.lastIndexOf("."));

// System.out.println(ext);

// 产生新文件名,用系统当前时间+文件原有后缀名

long newFileName = System.currentTimeMillis();

String newFileFullName = newFileName + ext;

// System.out.println("new file name:"+newFileFullName);

this.ftpFileName = newFileFullName;

try {

String savefilename = new String(localFileFullName

.getBytes("ISO-8859-1"), "GBK");

// 新建一个FTP客户端连接

ftpClient = new FtpClient();

ftpClient.openServer(this.ip);

ftpClient.login(this.username, this.password);

// 判断并创建目录

if (!isDirExist(this.ftpDir, ftpClient)) {

createDir(this.ftpDir, ftpClient);

}

ftpClient.cd(this.ftpDir);// 切换到FTP目录

ftpClient.binary();

os = ftpClient.put(this.ftpFileName);

// 打开本地待长传的文件

File file_in = new File(savefilename);

is = new FileInputStream(file_in);

byte[] bytes = new byte[1024];

// 开始复制

int c;

// 暂未考虑中途终止的情况

while ((c = is.read(bytes)) != -1) {

os.write(bytes, 0, c);

}

} catch (Exception e) {

e.printStackTrace();

System.err.println("Exception e in Ftp upload(): " + e.toString());

} finally {

try {

if (is != null) {

is.close();

}

if (os != null) {

os.close();

}

if (ftpClient != null) {

ftpClient.closeServer();

}

} catch (Exception e) {

System.err.println("Exception e in Ftp upload() finally"

+ e.toString());

}

}

return this.ftpFileName;

}

public void delFile(String dir, String filename) {

ftpClient = new FtpClient();

try {

ftpClient.openServer(this.ip);

ftpClient.login(this.username, this.password);

if (dir.length() 0) {

ftpClient.cd(dir);

}

ftpClient.sendServer("DELE " + filename + "\r\n");

ftpClient.readServerResponse();

} catch (IOException e) {

// TODO 自动生成 catch 块

e.printStackTrace();

}

}

}

我写的一个FTP类,你看看你能不能用。。。。。


名称栏目:关于javaftp代码示列的信息
转载源于:http://bjjierui.cn/article/hjegdh.html

其他资讯