Java应用程序开发包实现FTP服务器端程序,提供文件传输服务和相应的统计数据。简单的用户界面和统计功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java应用程序开发包实现FTP服务器端程序,提供文件传输服务和相应的统计数据。简单的用户界面和统计功能相关的知识,希望对你有一定的参考价值。

希望有源代码,因为是毕业设计所以比较急。又因为自己不是很懂,所以谢谢各位了。。。帮个忙

用Java实现FTP服务器
2004-03-10 02:09 来源:eNet论坛

【简 介】
FTP(File Transfer Protocol 文件传输协议)是Internet 上用来传送文件的协议。在Internet上通过FTP 服务器可以进行文件的上传(Upload)或下载(Download)。FTP是实时联机服务,在使用它之前必须是具有该服务的一个用户(用户名和口令),工作时客户端必须先登录到作为服务器一方的计算机上,用户登录后可以进行文件搜索和文件传送等有关操作,如改变当前工作目录、列文件目录、设置传输参数及传送文件等。使用FTP可以传送所有类型的文件,如文本文件、二进制可执行文件、图象文件、声音文件和数据压缩文件等。

加入收藏 设为首页

--------------------------------------------------------------------------------

FTP 命令

FTP 的主要操作都是基于各种命令基础之上的。常用的命令有:

◆ 设置传输模式,它包括ASCⅡ(文本) 和BINARY 二进制模式;

◆ 目录操作,改变或显示远程计算机的当前目录(cd、dir/ls 命令);

◆ 连接操作,open命令用于建立同远程计算机的连接;close命令用于关闭连接;

◆ 发送操作,put命令用于传送文件到远程计算机;mput 命令用于传送多个文件到远程计算机;

◆ 获取操作,get命令用于接收一个文件;mget命令用于接收多个文件。

编程思路

根据FTP 的工作原理,在主函数中建立一个服务器套接字端口,等待客户端请求,一旦客户端请求被接受,服务器程序就建立一个服务器分线程,处理客户端的命令。如果客户端需要和服务器端进行文件的传输,则建立一个新的套接字连接来完成文件的操作。

编程技巧说明

1.主函数设计

在主函数中,完成服务器端口的侦听和服务线程的创建。我们利用一个静态字符串变量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)

2. 线程类的设计

线程类的主要设计都是在run()方法中实现。用run()方法得到客户端的套接字信息,根据套接字得到输入流和输出流,向客户端发送欢迎信息。

3. FTP 命令的处理

(1) 访问控制命令

◆ user name(user) 和 password (pass) 命令处理代码如下:

if(str.startsWith("USER"))
user = str.substring(4);
user = user.trim();
out.println("331 Password");
if(str.startsWith("PASS"))
out.println("230 User "+user+" logged in.");

User 命令和 Password 命令分别用来提交客户端用户输入的用户名和口令。

◆ CWD (CHANGE WORKING DIRECTORY) 命令处理代码如下:

if(str.startsWith("CWD"))
String str1 = str.substring(3);
dir = dir+"/"+str1.trim();
out.println("250 CWD command succesful");


该命令改变工作目录到用户指定的目录。

◆ CDUP (CHANGE TO PARENT DIRECTORY) 命令处理代码如下:

if(str.startsWith("CDUP"))
int n = dir.lastIndexOf("/");
dir = dir.substring(0,n);
out.println("250 CWD command succesful");


该命令改变当前目录为上一层目录。

◆ QUIT命令处理代码如下:

if(str.startsWith("QUIT"))
out.println("GOOD BYE");
done = true;


该命令退出及关闭与服务器的连接,输出GOOD BYE。

(2) 传输参数命令

◆ Port命令处理代码如下:

if(str.startsWith("PORT"))
out.println("200 PORT command successful");
int i = str.length() - 1;
int j = str.lastIndexOf(",");
int k = str.lastIndexOf(",",j-1);
String str1,str2;
str1="";
str2="";
for(int l=k+1;l
str1 = str2 + str.charAt(l);

for(int l=j+1;l<=i;l++)
str2 = str2 + str.charAt(l);

tempPort = Integer.parseInt(str1) * 16 *16 +Integer.parseInt(str2);


使用该命令时,客户端必须发送客户端用于接收数据的32位IP 地址和16位 的TCP 端口号。这些信息以8位为一组,使用十进制传输,中间用逗号隔开。

◆ TYPE命令处理代码如下:

if(str.startsWith("TYPE"))
out.println("200 type set");


TYPE 命令用来完成类型设置。

(3) FTP 服务命令

◆ RETR (RETEIEVE) 和 STORE (STORE)命令处理的代码

if(str.startsWith("RETR"))
out.println("150 Binary data connection");
str = str.substring(4);
str = str.trim();
RandomAccessFile outFile = new
RandomAccessFile(dir+"/"+str,"r");
Socket tempSocket = new Socket(host,tempPort);
OutputStream outSocket
= tempSocket.getOutputStream();
byte byteBuffer[]= new byte[1024];
int amount;
try
while((amount = outFile.read(byteBuffer)) != -1)
outSocket.write(byteBuffer, 0, amount);

outSocket.close();
out.println("226 transfer complete");
outFile.close();
tempSocket.close();

catch(IOException e)

if(str.startsWith("STOR"))
out.println("150 Binary data connection");
str = str.substring(4);
str = str.trim();
RandomAccessFile inFile = new
RandomAccessFile(dir+"/"+str,"rw");
Socket tempSocket = new Socket(host,tempPort);
InputStream inSocket
= tempSocket.getInputStream();
byte byteBuffer[] = new byte[1024];
int amount;
try
while((amount =inSocket.read(byteBuffer) )!= -1)
inFile.write(byteBuffer, 0, amount);

inSocket.close();
out.println("226 transfer complete");
inFile.close();
tempSocket.close();

catch(IOException e)


文件传输命令包括从服务器中获得文件RETR和向服务器中发送文件STOR,这两个命令的处理非常类似。处理RETR命令时,首先得到用户要获得的文件的名称,根据名称创建一个文件输入流,然后和客户端建立临时套接字连接,并得到一个输出流。随后,将文件输入流中的数据读出并借助于套接字输出流发送到客户端,传输完毕以后,关闭流和临时套接字。

STOR 命令的处理也是同样的过程,只是方向正好相反。

◆ DELE (DELETE)命令处理代码如下:

if(str.startsWith("DELE"))
str = str.substring(4);
str = str.trim();
File file = new File(dir,str);
boolean del = file.delete();
out.println("250 delete command successful");


DELE 命令用于删除服务器上的指定文件。

◆ LIST命令处理代码如下:

if(str.startsWith("LIST"))
try
out.println("150 ASCII data");
Socket tempSocket = new Socket(host,tempPort);
PrintWriter out2= new PrintWriter(tempSocket.getOutputStream(),true);
File file = new File(dir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String strType="";
for(int i=0;i
if( dirStructure[i].indexOf(".") == -1)
strType = "d ";
else
strType = "- ";
out2.println(strType+dirStructure[i]);

tempSocket.close();
out.println("226 transfer complete");

catch(IOException e)

LIST 命令用于向客户端返回服务器中工作目录下的目录结构,包括文件和目录的列表。处理这个命令时,先创建一个临时的套接字向客户端发送目录信息。这个套接字的目的端口号缺省为1,然后为当前工作目录创建File 对象,利用该对象的list()方法得到一个包含该目录下所有文件和子目录名称的字符串数组,然后根据名称中是否含有文件名中特有的“.”来区别目录和文件。最后,将得到的名称数组通过临时套接字发送到客户端。

参考资料:http://www.enet.com.cn/article/2004/0310/A20040310293160.shtml

参考技术A 看看ftp4j

怎样用java开发ftp客户端

要做毕业设计,希望能提供详细的参考资料,源码,有教程最好.
Java基本编程懂,但是网络相关的没怎么做过,所以要找入门教程,程序范例.网上搜的太杂,没一个好使的.
毕业设计催得又紧,只能求助各位大虾了.

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.DefaultListModel;
import javax.swing.JTree;

import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpLoginException;

public class Ttt
extends JFrame
implements ActionListener

FtpClient ftp = null;

private List list = new List();

private JPanel FtpClientFrame = new JPanel(new BorderLayout());
private JPanel FtpClientFrameOne = new JPanel(new FlowLayout(FlowLayout.
LEFT));
private JPanel FtpClientFrameTwo = new JPanel(new GridLayout(1, 8));
private JPanel FtpClientFrameThree = new JPanel(new GridLayout(2, 1));
private JPanel FtpClientFrameFour = new JPanel(new GridLayout(1, 2));

//连接、断开按钮
private JButton linkButton = new JButton("Link");
private JButton breakButton = new JButton("Break");
//连接状态
private JLabel statusLabel = new JLabel();
//用户登录
private JLabel urlLabel = new JLabel("Ftp URL:");
private JLabel usernameLabel = new JLabel("username:");
private JLabel passwordLabel = new JLabel("password:");
private JLabel portLabel = new JLabel("port:");
private JTextField urlTextField = new JTextField(10);
private JTextField usernameTextField = new JTextField(10);
private JTextField passwordTextField = new JTextField(10);
private JTextField portTextField = new JTextField(10);
//本地、远程窗口
DefaultListModel modelList = new DefaultListModel();
private JList localList = new JList();
private JList distanceList = new JList();
JScrollPane localScrollPane = new JScrollPane(localList);
JScrollPane distanceScrollPane = new JScrollPane(distanceList);
//本地、远程目录树
private JTree localTree;
private JTree ServerTree;

public Ttt()

FtpClientFrameOne.add(linkButton);
FtpClientFrameOne.add(breakButton);
FtpClientFrameOne.add(statusLabel);

FtpClientFrameTwo.add(urlLabel);
FtpClientFrameTwo.add(urlTextField);
FtpClientFrameTwo.add(usernameLabel);
FtpClientFrameTwo.add(usernameTextField);
FtpClientFrameTwo.add(passwordLabel);
FtpClientFrameTwo.add(passwordTextField);
FtpClientFrameTwo.add(portLabel);
FtpClientFrameTwo.add(portTextField);

FtpClientFrameThree.add(FtpClientFrameOne);
FtpClientFrameThree.add(FtpClientFrameTwo);

FtpClientFrameFour.add(localScrollPane);
FtpClientFrameFour.add(list);

FtpClientFrame.add(FtpClientFrameThree, "North");
FtpClientFrame.add(FtpClientFrameFour, "Center");

setContentPane(FtpClientFrame);
setTitle("Ftp客户端");
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

linkButton.addActionListener(this);
breakButton.addActionListener(this);


public String getDir(String path)
String dirName;
int ch;
int begin = 55;
dirName = path.substring(begin).trim();
return dirName;


public void loadList()
StringBuffer buf = new StringBuffer();
int ch;
list.removeAll();
try
TelnetInputStream t = ftp.list();
t.setStickyCRLF(true);
while ( (ch = t.read()) >= 0)
if (ch == '\n')
list.add(getDir(buf.toString()));
buf.setLength(0);

else
buf.append( (char) ch);




catch (IOException e)
e.printStackTrace();

list.validate();


public void actionPerformed(ActionEvent evt)
Object source = evt.getSource();
if (source == linkButton)
//连接Ftp服务器

try
if (ftp != null)
ftp.closeServer();
statusLabel.setText("连接中,请等待.....");
ftp = new FtpClient(urlTextField.getText());
ftp.login(usernameTextField.getText(),
passwordTextField.getText());
ftp.binary();

catch (FtpLoginException e)
JOptionPane.showMessageDialog(null, "Login Failure!!!");
e.printStackTrace();

catch (IOException e)
JOptionPane.showMessageDialog(null,
urlTextField.getText() + "Connection Failure!!!");
e.printStackTrace();

catch (SecurityException e)
JOptionPane.showMessageDialog(null, "No Purview!!!");
e.printStackTrace();

if (urlTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "Ftp服务器地址不能空!!!");
else if (usernameTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "用户名不能为空!!!");
else if (passwordTextField.getText().equals(""))
JOptionPane.showMessageDialog(null, "密码不能为空!!!");
else
statusLabel.setText("已连接到Ftp:" + urlTextField.getText());
loadList();

if (source == breakButton)
System.exit(0);



public static void main(String[] args)
// TODO Auto-generated method stub
Ttt ftpClientFrame = new Ttt();




收集的一些代码,忘记从拿来的了` 你可以看看
参考技术A package zn.ccfccb.util;
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import zn.ccfccb.util.CCFCCBUtil;
import zn.ccfccb.util.ZipUtilAll;

public class CCFCCBFTP

/**
* 上传文件
*
* @param fileName
* @param plainFilePath 明文文件路径路径
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1)
bos.write(buffer, 0, count);

bos.flush();
Log.info("加密上传文件开始");
Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// Log.info("连接远程上传服务器"+"192.168.54.106:"+2021);
// ftpClient.connect("192.168.54.106", 2021);
// ftpClient.login("hkrt-CCFCCBHK", "3OLJheziiKnkVcu7Sigz");
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs)
if (ff.getName().equals(filepath))
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");


Log.info("检查文件路径是否存在:/"+filepath);
if("false".equals(bl))
ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);
return bl;

ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");
return bl;
catch (Exception e)
throw e;
finally
if (fis != null)
try
fis.close();
catch (Exception e)
Log.info(e.getLocalizedMessage(), e);


if (bos != null)
try
bos.close();
catch (Exception e)
Log.info(e.getLocalizedMessage(), e);






/**
*下载并解压文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try
Log.info("下载并解密文件开始");
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;

ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs)
if (ff.getName().equals(fileName))
bl = "true";
Log.info("下载文件开始。");
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1)
bos.write(buffer, 0, count);

bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下载文件结束:"+localFilePath);


Log.info("检查文件是否存:"+fileName+" "+bl);
if("false".equals(bl))
ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");
return bl;

return bl;
catch (Exception e)
throw e;
finally
if (fis != null)
try
fis.close();
catch (Exception e)
Log.info(e.getLocalizedMessage(), e);


if (bos != null)
try
bos.close();
catch (Exception e)
Log.info(e.getLocalizedMessage(), e);


if (fos != null)
try
fos.close();
catch (Exception e)
Log.info(e.getLocalizedMessage(), e);





// 调用样例:
public static void main(String[] args)
try
// 密钥/res/20150228
// ZipUtilAll.unZip(new File(("D:/123/123.zip")), "D:/123/");
// ZipDemo1232.unZip(new File(("D:/123/123.zip")), "D:/123/");
// 明文文件路径
String plainFilePath = "D:/req_20150204_0011.txt";
// 密文文件路径
String secretFilePath = "req_20150204_00134.txt";
// 加密
// encodeAESFile(key, plainFilePath, secretFilePath);
fileDownloadByFtp("D://123.zip","123.zip","req/20150228");
ZipUtilAll.unZip("D://123.zip", "D:/123/李筱/");
// 解密
plainFilePath = "D:/123.sql";
// secretFilePath = "D:/test11111.sql";
// decodeAESFile(key, plainFilePath, secretFilePath);
catch (Exception e)
e.printStackTrace();



参考技术B 买本java web开发详解
看了一下656页有上传下载例子

以上是关于Java应用程序开发包实现FTP服务器端程序,提供文件传输服务和相应的统计数据。简单的用户界面和统计功能的主要内容,如果未能解决你的问题,请参考以下文章

java操作ftp上传下载

Servelt动态Web资源开发技术(java程序运行在服务器端)

IOCP 浅析(java代码实现)

用python实现FTP功能

Java实现FTP客户端,获得IP和端口号的问题

java在浏览器上获取FTP读文件路径