当前位置:首页 » 文件管理 » javaftp开发

javaftp开发

发布时间: 2023-05-25 22:47:58

❶ 怎么用java实现ftp上传

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

/**
* 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");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上传成功!" : "上传失败!");
ftp.closeServer();
/**
* 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服务器

FTP(File Transfer Protocol 文件传输协议)是Internet 上用来传送文件的协议。在Internet上通过FTP 服务器可以进行文件的上传(Upload)或下载(Download)。FTP是实时联机服务,在使用它之前必须是具有该服务的一个用户(用户名和口令),工作时客户端必须先登录到作为服务器一方的计算机上,用户登录后可以进行文件搜索和文件传送等有关操作,如改变当前工作目录、列文件目录、设置传输参数及传送文件等。使用FTP可以传送所有类型的文件,如文本文件、二进制可执行文件、图象文件、声音文件和数据压缩文件等。
FTP 命令
FTP 的主要操作都是基于各种命令基础之上的。常用的命令有:
设置传输模式,它包括ASCⅡ(文本) 和BINARY 二进制模式;
目录操作,改变或显示远程计算机的当前目录(cd、dir/ls 命令);
连接操作,open命令用于建立同远程计算机的连接;close命令用于关闭连接;
发送操作,put命令用于传送文件到远程计算机;mput 命令用于传送多个文件到远程计算机;
获取操作,get命令用于接收一个文件;mget命令用于接收多个文件。
?


import java.net.Socket;import org.apache.log4j.Logger;/** * 角色——服务器A * @author Leon * */public class ServerA{ public static void main(String[] args){ final String F_DIR = "c:/test";//根路径 final int PORT = 22;//监听端口号 Logger.getRootLogger(); Logger logger = Logger.getLogger("com"); try{ ServerSocket s = new ServerSocket(PORT); logger.info("Connecting to server A..."); logger.info("Connected Successful! Local Port:"+s.getLocalPort()+". Default Directory:'"+F_DIR+"'."); while( true ){ //接受客户端请求 Socket client = s.accept(); //创建服务线程 new ClientThread(client, F_DIR).start(); } } catch(Exception e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } }}import java.io.BufferedReader; import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.io.RandomAccessFile;import java.net.ConnectException;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import java.nio.charset.Charset;import java.util.Random;import org.apache.log4j.Logger;/** * 客户端子线程类 * @author Leon * */public class ClientThread extends Thread { private Socket socketClient;//客户端socket private Logger logger;//日志对象 private String dir;//绝对路径 private String pdir = "/";//相对路径 private final static Random generator = new Random();//随机数 public ClientThread(Socket client, String F_DIR){ this.socketClient = client; this.dir = F_DIR; } @Override public void run() { Logger.getRootLogger(); logger = Logger.getLogger("com"); InputStream is = null; OutputStream os = null; try { is = socketClient.getInputStream(); os = socketClient.getOutputStream(); } catch (IOException e) { logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } } BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); PrintWriter pw = new PrintWriter(os); String clientIp = socketClient.getInetAddress().toString().substring(1);//记录客户端IP String username = "not logged in";//用户名 String password = "";//口令 String command = "";//命令 boolean loginStuts = false;//登录状态 final String LOGIN_WARNING = "530 Please log in with USER and PASS first."; String str = "";//命令内容字符串 int port_high = 0; int port_low = 0; String retr_ip = "";//接收文件的IP地址 Socket tempsocket = null; //打印欢迎信息 pw.println("220-FTP Server A version 1.0 written by Leon Guo"); pw.flush(); logger.info("("+username+") ("+clientIp+")> Connected, sending welcome message..."); logger.info("("+username+") ("+clientIp+")> 220-FTP Server A version 1.0 written by Leon Guo"); boolean b = true; while ( b ){ try { //获取用户输入的命令 command = br.readLine(); if(null == command) break; } catch (IOException e) { pw.println("331 Failed to get command"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 331 Failed to get command"); logger.error(e.getMessage()); for(StackTraceElement ste : e.getStackTrace()){ logger.error(ste.toString()); } b = false; } /* * 访问控制命令 */ // USER命令 if(command.toUpperCase().startsWith("USER")){ logger.info("(not logged in) ("+clientIp+")> "+command); username = command.substring(4).trim(); if("".equals(username)){ pw.println("501 Syntax error"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 501 Syntax error"); username = "not logged in"; } else{ pw.println("331 Password required for " + username); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 331 Password required for " + username); } loginStuts = false; } //end USER // PASS命令 else if(command.toUpperCase().startsWith("PASS")){ logger.info("(not logged in) ("+clientIp+")> "+command); password = command.substring(4).trim(); if(username.equals("root") && password.equals("root")){ pw.println("230 Logged on"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 230 Logged on");// logger.info("客户端 "+clientIp+" 通过 "+username+"用户登录"); loginStuts = true; } else{ pw.println("530 Login or password incorrect!"); pw.flush(); logger.info("(not logged in) ("+clientIp+")> 530 Login or password incorrect!"); username = "not logged in"; } } //end PASS // PWD命令 else if(command.toUpperCase().startsWith("PWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){// logger.info("用户"+clientIp+":"+username+"执行PWD命令"); pw.println("257 /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 257 /""+pdir+"/" is current directory"); } else{ pw.println(LOGIN_WARNING); pw.flush(); logger.info("("+username+") ("+clientIp+")> "+LOGIN_WARNING); } } //end PWD // CWD命令 else if(command.toUpperCase().startsWith("CWD")){ logger.info("("+username+") ("+clientIp+")> "+command); if(loginStuts){ str = command.substring(3).trim(); if("".equals(str)){ pw.println("250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 Broken client detected, missing argument to CWD. /""+pdir+"/" is current directory."); } else{ //判断目录是否存在 String tmpDir = dir + "/" + str; File file = new File(tmpDir); if(file.exists()){//目录存在 dir = dir + "/" + str; if("/".equals(pdir)){ pdir = pdir + str; } else{ pdir = pdir + "/" + str; }// logger.info("用户"+clientIp+":"+username+"执行CWD命令"); pw.println("250 CWD successful. /""+pdir+"/" is current directory"); pw.flush(); logger.info("("+username+") ("+clientIp+")> 250 CWD successful. /""+pdir+"/" is current directory"); } else{//目录不存在 pw.println("550 CWD failed. /""+pdir+"/": directory not found."); pw.flush(); logger.info("("+username+") ("+clientIp+")> 550 CWD failed. /""+pdir+"/": directory not found.");

❸ 怎样用java开发ftp客户端

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();
}
}

}

❹ java开发ftp客户端对服务器文件状态如何识别

我们当时是这样处理的:

上传一个文件,比如名字为:aaa.rar
当文件上传完的时候就会上传一个aaa.fin的空文件做标识,表明这个文件上传成功。

下载的时候首先检查aaa.fin是否存在。然后下载!

建议你在文件目录下放一个list.xml(存放当前上传成功的文件名,下载前在里面检索它是否存在)

❺ 求用java写一个ftp服务器客户端程序。

import java.io.*;
import java.net.*;public class ftpServer extends Thread{ public static void main(String args[]){
String initDir;
initDir = "D:/Ftp";
ServerSocket server;
Socket socket;
String s;
String user;
String password;
user = "root";
password = "123456";
try{
System.out.println("MYFTP服务器启动....");
System.out.println("正在等待连接....");
//监听21号端口
server = new ServerSocket(21);
socket = server.accept();
System.out.println("连接成功");
System.out.println("**********************************");
System.out.println("");

InputStream in =socket.getInputStream();
OutputStream out = socket.getOutputStream();

DataInputStream din = new DataInputStream(in);
DataOutputStream dout=new DataOutputStream(out);
System.out.println("请等待验证客户信息....");

while(true){
s = din.readUTF();
if(s.trim().equals("LOGIN "+user)){
s = "请输入密码:";
dout.writeUTF(s);
s = din.readUTF();
if(s.trim().equals(password)){
s = "连接成功。";
dout.writeUTF(s);
break;
}
else{s ="密码错误,请重新输入用户名:";<br> dout.writeUTF(s);<br> <br> }
}
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}
System.out.println("验证客户信息完毕...."); while(true){
System.out.println("");
System.out.println("");
s = din.readUTF();
if(s.trim().equals("DIR")){
String output = "";
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
for(int i=0;i<dirStructure.length;i++){
output +=dirStructure[i]+"\n";
}
s=output;
dout.writeUTF(s);
}
else if(s.startsWith("GET")){
s = s.substring(3);
s = s.trim();
File file = new File(initDir);
String[] dirStructure = new String[10];
dirStructure= file.list();
String e= s;
int i=0;
s ="不存在";
while(true){
if(e.equals(dirStructure[i])){
s="存在";
dout.writeUTF(s);
RandomAccessFile outFile = new RandomAccessFile(initDir+"/"+e,"r");
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
dout.write(byteBuffer, 0, amount);break;
}break;

}
else if(i<dirStructure.length-1){
i++;
}
else{
dout.writeUTF(s);
break;
}
}
}
else if(s.startsWith("PUT")){
s = s.substring(3);
s = s.trim();
RandomAccessFile inFile = new RandomAccessFile(initDir+"/"+s,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
while((amount =din.read(byteBuffer) )!= -1){
inFile.write(byteBuffer, 0, amount);break;
}
}
else if(s.trim().equals("BYE"))break;
else{
s = "您输入的命令不正确或此用户不存在,请重新输入:";
dout.writeUTF(s);
}
}

din.close();
dout.close();
in.close();
out.close();
socket.close();
}
catch(Exception e){
System.out.println("MYFTP关闭!"+e);

}
}}

❻ 使用Java实现FTP服务器

FTP是Internet 上用来传送文件的协议 在Internet上通过FTP 服务器可以进行文件的上传(Upload)或下载(Download) FTP是实时联机服务 在使用它之前必须是具有该服务的一个用户(用户名和口令) 工作时客户端必须先登录到作为服务器一方的计算机上 用户登录后可以进行文件搜索和文件传送等有关操作 如改变当前工作目录 列文件目录 设置传输参数及传送文件等 使用FTP可以传送所有类型的文件 如文本文件 二进制可执行文件 图象文件 声音文件和数据压缩文件等 FTP 命令 FTP 的主要操作都是基于各种命令基础之上的 常用的命令有 ◆ 设置传输模式 它包括ASCⅡ(文本) 和BINARY 二进制模式 ◆ 目录操作 改变或显示远程计算机的当前目录(cd dir/ls 命令) ◆ 连接操作 open命令用于建立同远程计算机的连接 close命令用于关闭连接 ◆ 发送操作 put命令用于传送文件到远程计算机 mput 命令用于传送多个文件到远程计算机 ◆ 获取操作 get命令用于接收一个文件 mget命令用于接收多个文件 编程思路 根据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 != ) { initDir = args[ ]; }else{ initDir = c: ;} int i = ; try{ System out println( ftp server started! ) //监听 号端口 ServerSocket s = new ServerSocket( ) for( ){ //接受客户端请求 Socket ining = s accept() //创建服务线程 new ftpServer(ining i) start() i++; } }catch(Exception e){} } 线程类的设计 线程类的主要设计都是在run()方法中实现 用run()方法得到客户端的套接字信息 根据套接字得到输入流和输出流 向客户端发送欢迎信息 FTP命令的处理 ( ) 访问控制命令 ◆ user name(user) 和 password (pass) 命令处理代码如下 if(str startsWith( USER )){ user = str substring( ) user = user trim() out println( Password ) } if(str startsWith( PASS )) out println( User +user+ logged in ) User 命令和 Password 命令分别用来提交客户端用户输入的用户名和口令 ◆ CWD (CHANGE WORKING DIRECTORY) 命令处理代码如下 if(str startsWith( CWD )){ String str = str substring( ) dir = dir+ / +str trim() out println( CWD mand succesful ) } 该命令改变工作目录到用户指定的目录 ◆ CDUP (CHANGE TO PARENT DIRECTORY) 命令处理代码如下 if(str startsWith( CDUP )){ int n = dir lastIndexOf( / ) dir = dir substring( n) out println( CWD mand succesful ) } 该命令改变当前目录为上一层目录 ◆ QUIT命令处理代码如下 if(str startsWith( QUIT )) { out println( GOOD BYE ) done = true;} 该命令退出及关闭与服务器的连接 输出GOOD BYE

( ) 传输参数命令 ◆ Port命令处理代码如下 if(str startsWith( PORT )) { out println( PORT mand successful ) int i = str length() ; int j = str lastIndexOf( ) int k = str lastIndexOf( j ) String str str ;str = ; str = ;for(int l=k+ ; lstr = str + str charAt(l) } for(int l=j+ ;l<=i;l++){ str = str + str charAt(l) } tempPort = Integer parseInt(str ) * * +Integer parseInt(str ) } 使用该命令时 客户端必须发送客户端用于接收数据的 位IP 地址和 位 的TCP 端口号 这些信息以 位为一组 使用十进制传输 中间用逗号隔开 ◆ TYPE命令处理代码如下 if(str startsWith( TYPE )){ out println( type set ) } TYPE 命令用来完成类型设置 ( ) FTP 服务命令 ◆ RETR (RETEIEVE) 和 STORE (STORE)命令处理的代码 if(str startsWith( RETR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile outFile = newRandomAccessFile(dir+ / +str r ) Socket tempSocket = new Socket(host tempPort) OutputStream outSocket= tempSocket getOutputStream() byte byteBuffer[]= new byte[ ]; int amount; try{ while((amount = outFile read(byteBuffer)) != ){

outSocket write(byteBuffer amount) } outSocket close() out println( transfer plete ) outFile close() tempSocket close() } catch(IOException e){} } if(str startsWith( STOR )){ out println( Binary data connection ) str = str substring( ) str = str trim() RandomAccessFile inFile = newRandomAccessFile(dir+ / +str rw ) Socket tempSocket = new Socket(host tempPort) InputStream inSocket= tempSocket getInputStream() byte byteBuffer[] = new byte[ ]; int amount; try{ while((amount =inSocket read(byteBuffer) )!= ){ inFile write(byteBuffer amount) } inSocket close() out println( transfer plete ) inFile close() tempSocket close() } catch(IOException e) {} } 文件传输命令包括从服务器中获得文件RETR和向服务器中发送文件STOR 这两个命令的处理非常类似 处理RETR命令时 首先得到用户要获得的文件的名称 根据名称创建一个文件输入流 然后和客户端建立临时套接字连接 并得到一个输出流 随后 将文件输入流中的数据读出并借助于套接字输出流发送到客户端 传输完毕以后 关闭流和临时套接字 STOR 命令的处理也是同样的过程 只是方向正好相反 ◆ DELE (DELETE)命令处理代码如下 if(str startsWith( DELE )){ str = str substring( ) str = str trim() File file = new File(dir str) boolean del = file delete() out println( delete mand successful ) } DELE 命令用于删除服务器上的指定文件 ◆ LIST命令处理代码如下 if(str startsWith( LIST )) { try{ out println( ASCII data ) Socket tempSocket = new Socket(host tempPort) PrintWriter out = new PrintWriter(tempSocket getOutputStream() true) File file = new File(dir) String[] dirStructure = new String[ ]; dirStructure= file list() String strType= ; for(int i= ;iif( dirStructure[i] indexOf( ) == ) { strType = d ;} else{ strType = ;} out println(strType+dirStructure[i]) } tempSocket close() out println( transfer plete ) } catch(IOException e) {} LIST 命令用于向客户端返回服务器中工作目录下的目录结构 包括文件和目录的列表 处理这个命令时 先创建一个临时的套接字向客户端发送目录信息 这个套接字的目的端口号缺省为 然后为当前工作目录创建File 对象 利用该对象的list()方法得到一个包含该目录下所有文件和子目录名称的字符串数组 然后根据名称中是否含有文件名中特有的 来区别目录和文件 最后 将得到的名称数组通过临时套接字发送到客户端 lishixin/Article/program/Java/hx/201311/26847

❼ JAVA 如何实现FTP远程路径

package nc.ui.doc.doc_007;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import nc.itf.doc.DocDelegator;
import nc.vo.doc.doc_007.DirVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTP;

public class FtpTool {

private FTPClient ftp;

private String romateDir = "";

private String userName = "";

private String password = "";

private String host = "";

private String port = "21";

public FtpTool(String url) throws IOException {
//String url="ftp://user:password@ip:port/ftptest/psd";
int len = url.indexOf("//");
String strTemp = url.substring(len + 2);
len = strTemp.indexOf(":");
userName = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);

len = strTemp.indexOf("@");
password = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
host = "";
len = strTemp.indexOf(":");
if (len < 0)//没有设置端口
{
port = "21";
len = strTemp.indexOf("/");
if (len > -1) {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
strTemp = "";
}
} else {
host = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
len = strTemp.indexOf("/");
if (len > -1) {
port = strTemp.substring(0, len);
strTemp = strTemp.substring(len + 1);
} else {
port = "21";
strTemp = "";
}
}
romateDir = strTemp;
ftp = new FTPClient();
ftp.connect(host, FormatStringToInt(port));

}

public FtpTool(String host, int port) throws IOException {
ftp = new FTPClient();
ftp.connect(host, port);
}

public String login(String username, String password) throws IOException {
this.ftp.login(username, password);
return this.ftp.getReplyString();
}

public String login() throws IOException {
this.ftp.login(userName, password);
System.out.println("ftp用户: " + userName);
System.out.println("ftp密码: " + password);
if (!romateDir.equals(""))
System.out.println("cd " + romateDir);
ftp.changeWorkingDirectory(romateDir);
return this.ftp.getReplyString();
}

public boolean upload(String pathname, String filename) throws IOException, BusinessException {

int reply;
int j;
String m_sfilename = null;
filename = CheckNullString(filename);
if (filename.equals(""))
return false;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.out.println("FTP server refused connection.");
System.exit(1);
}
FileInputStream is = null;
try {
File file_in;
if (pathname.endsWith(File.separator)) {
file_in = new File(pathname + filename);
} else {
file_in = new File(pathname + File.separator + filename);
}
if (file_in.length() == 0) {
System.out.println("上传文件为空!");
return false;
}
//产生随机数最大到99
j = (int)(Math.random()*100);
m_sfilename = String.valueOf(j) + ".pdf"; // 生成的文件名
is = new FileInputStream(file_in);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.storeFile(m_sfilename, is);
ftp.logout();

} finally {
if (is != null) {
is.close();
}
}
System.out.println("上传文件成功!");
return true;
}

public boolean delete(String filename) throws IOException {

FileInputStream is = null;
boolean retValue = false;
try {
retValue = ftp.deleteFile(filename);
ftp.logout();
} finally {
if (is != null) {
is.close();
}
}
return retValue;

}

public void close() {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static int FormatStringToInt(String p_String) {
int intRe = 0;
if (p_String != null) {
if (!p_String.trim().equals("")) {
try {
intRe = Integer.parseInt(p_String);
} catch (Exception ex) {

}
}
}
return intRe;
}

public static String CheckNullString(String p_String) {
if (p_String == null)
return "";
else
return p_String;
}

public boolean downfile(String pathname, String filename) {

String outputFileName = null;
boolean retValue = false;
try {
FTPFile files[] = ftp.listFiles();
int reply = ftp.getReplyCode();

////////////////////////////////////////////////
if (!FTPReply.isPositiveCompletion(reply)) {
try {
throw new Exception("Unable to get list of files to dowload.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/////////////////////////////////////////////////////
if (files.length == 0) {
System.out.println("No files are available for download.");
}else {
for (int i=0; i <files.length; i++) {
System.out.println("Downloading file "+files[i].getName()+"Size:"+files[i].getSize());
outputFileName = pathname + filename + ".pdf";
//return outputFileName;
File f = new File(outputFileName);

//////////////////////////////////////////////////////
retValue = ftp.retrieveFile(outputFileName, new FileOutputStream(f));

if (!retValue) {
try {
throw new Exception ("Downloading of remote file"+files[i].getName()+" failed. ftp.retrieveFile() returned false.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}

/////////////////////////////////////////////////////////////
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retValue;
}

}

❽ 能否给一个java开发的具有图形界面的ftp服务器客户端源代码呢

/ **
*创建日期:2008年12月23日

*类名:Ftp.java

*类路径:组织结构

*更改日志:

* / 包组织结构;

进口的java.io.File;

进口java.io.FileInputStream中;

进口java.io.FileOutputStream中;

进口的java。 io.IOException;

进口sun.net.TelnetInputStream;

进口sun.net.TelnetOutputStream;

进口sun.net.ftp.FtpClient;

> / **

* @作者南山地狱

* @说明FTP操作

* /

公共类的Ftp {

/ **

* BR />获取FTP目录* / 公共无效getftpList(){

字符串服务器=“IP地址 /输入FTP服务器/>弦乐用户=”“;/ / FTP服务器的登录用户名

字符串密码=“”;/ /登录FTP服务器的用户名

字符串路径密码=“”;/ / FTP路径上的服务器

尝试{
> FtpClient的FTP客户端=新FtpClient的();/ /创建FtpClient的对象

ftpClient.openServer(服务器);/ /连接到FTP服务器

ftpClient.login(用户名,密码);/ / FTP服务器 BR />如果(path.length()= 0){

ftpClient.cd(路径);

}

TelnetInputStream是= ftpClient.list();

诠释三;

而{

System.out.print((char)的C)((C = is.read())= -1!);

}

掉} is.close ();

ftpClient.closeServer();/ /退出FTP服务器

}赶上(IOException异常前){

System.out.println(ex.getMessage());

}

}

/ **

*
* /

公共无效getFtpFile(){

字符串服务器=“”;/ / IP地址中输入FTP服务器

弦乐用户=“”;/ / FTP服务器的登录用户名

字符串密码=“”;/ /登录密码为FTP服务器的用户名

字符串路径=“路径

字符串文件名“;/ /上=的FTP服务器”“;/ /下载文件名称

尝试{

FtpClient的FTP客户端=新FtpClient的();

ftpClient.openServer(服务器);

ftpClient.login(用户名,密码);

如果(路径。长度()= 0)

ftpClient.cd(路径);!

ftpClient.binary();

TelnetInputStream是= ftpClient.get(文件名);

文件file_out =新的文件(文件名);

文件输出流OS =新的文件输出流(file_out);

字节[]字节=新字节[1024];

诠释三;

而((C = is.read(字节))= -1){

os.write (字节,0,C);

}!

掉} is.close();

os.close();

ftpClient.closeServer();

}赶上(IOException异常前){

System.out.println (ex.getMessage());

}

FTP}

/ **

*文件上传到FTP

* /

公共无效putFtpFile() {

字符串服务器=“”;/ /输入IP地址对服务器

字符串用户的地址=“”;/ / FTP服务器的登录用户名

字符串密码=“”;/ / FTP服务器登录用户名密码

字符串路径=“”就 / FTP服务器/>字符串文件名=“”;/ /上传的文件名

FtpClient的FTP客户端=新的try { FtpClient的();

ftpClient.openServer(服务器);

ftpClient.login(用户名,密码);

如果(!path.length()= 0)

ftpClient.cd (路径);

ftpClient.binary();

TelnetOutputStream OS = ftpClient.put(文件名);

文件file_in =新的文件(文件名);

文件输入流是=新的文件输入流(file_in);

字节[]字节=新字节[1024];

诠释三;

同时(! (C = is.read(字节))= -1){

操作系统。写(字节,0,C);

}

掉} is.close();

os.close();

ftpClient.closeServer();

}赶上(IOException异常前){

System.out.println(ex.getMessage());

}

}
}

热点内容
抖音青少年模式的密码是哪里的 发布:2024-05-07 10:05:27 浏览:751
tmp文件怎么解压 发布:2024-05-07 09:59:49 浏览:937
安卓手机如何提升录歌音质 发布:2024-05-07 09:49:55 浏览:330
指法运算法 发布:2024-05-07 09:24:26 浏览:195
兜享花为什么服务器错误 发布:2024-05-07 09:12:55 浏览:126
西门子编程仿真软件 发布:2024-05-07 09:12:04 浏览:128
脚本举例 发布:2024-05-07 09:04:41 浏览:819
php经历 发布:2024-05-07 08:59:25 浏览:420
knd系统编程 发布:2024-05-07 08:55:38 浏览:219
大话2无限自动脚本 发布:2024-05-07 08:42:06 浏览:79