📄 ftpclient.java
字号:
package com.rocket.usable;
import java.io.*;
import java.net.*;
public class ftpClient {
/**
* @param args
* 基本上实现了ftp的功能
* 定义了ftp的常用的上传和下载等功能,
* 暂时不支持断点续传等
* @author lihong
* @date 2008-03-16
*/
private Socket socket=null;
private String hosts="";
private int ports;
private String username="";
private String passwd="";
private String path="";
private BufferedReader buffRead=null;
private BufferedWriter buffWrite=null;
private boolean bConnect=false;
private String strMsg="";//服务器返回的信息(包含应答码)
private String strReply="";//服务器返回的信息(包含应答码)
private int iReplyCode;//服务器返回的应答码
final String separator=System.getProperty("line.separator"); //取系统换行符
private int buffSize=1024;
private String transType="";
static class transTypes{
public final static String ascii="ascii";
public final static String binary="binary";
}
public ftpClient(){
hosts="";
ports=0;
username="";
passwd="";
path="";
bConnect=false;
}
public ftpClient(String Hosts,int Ports,String username,
String password,String path)throws IOException{
this.hosts=Hosts;
this.ports=Ports;
this.username=username;
this.passwd=password;
this.path=path;
connect();
}
public void setBuffer(int buffSize){
this.buffSize=buffSize;
}
public int getBuffSize(){
return buffSize;
}
public void setHost(String hosts){
this.hosts=hosts;
}
public void setPort(int port){
this.ports=port;
}
public String getHost(){
return hosts;
}
public int getPort(){
return ports;
}
public void setUsername(String username){
this.username=username;
}
public String getUsername(){
return username;
}
public void setPassword(String passwd){
this.passwd=passwd;
}
public String getPassword(){
return passwd;
}
public void setPath(String path){
this.path=path;
}
public String getPath(){
return path;
}
//连接ftp服务器
public void connect () throws IOException{
try
{
socket=new Socket(hosts,ports);
readReplay();
if (iReplyCode!=220)
{
closeSocket();
return;
}
sendCommand("USER "+username.trim());
if (!(iReplyCode==230||iReplyCode==331))
{
closeSocket();
return;
}
if (iReplyCode!=230)
{
sendCommand("PASS "+passwd);
if (!(iReplyCode==230||iReplyCode==202))
{
closeSocket();
return;
}
}
bConnect=true;
chDir(path);
}catch(Exception e)
{
bConnect=false;
}
}
//取得当前连接状态
public boolean getConnectState(){
return bConnect;
}
//改变ftp目录
public void chDir(String path) throws IOException
{
if (path.equals(".") || path.equals(""))
{
closeSocket();
return;
}
if (!bConnect)
{
connect();
}
sendCommand("CWD "+path);
if (iReplyCode!=250)
{
closeSocket();
return;
}
this.path=path;
}
public void chUpDir() throws IOException
{
if (!bConnect)
{
connect();
}
sendCommand("CDUP");
if (iReplyCode!=250)
{
throw new IOException("返回到上级目录出错!");
}
}
public void mkDir(String strFolder) throws IOException
{
if (!bConnect)
{
connect();
}
sendCommand("MKD "+strFolder);
if (iReplyCode!=257)
{
throw new IOException("新建目录出错!");
}
}
public void rmDir(String strFolder) throws IOException
{
if (!bConnect)
{
connect();
}
sendCommand("RMD "+strFolder);
if (iReplyCode!=250)
{
throw new IOException("删除目录出错!");
}
}
//关闭连接
private void closeSocket()throws IOException{
if (socket!=null)
{
socket.close();
socket=null;
buffRead.close();
buffWrite.close();
bConnect=false;
}
}
//取得传输类型
public String getTransType(){
return transType;
}
//设置传输类型 ascii binary
public void setTransType(String transType) throws IOException
{
if (!(transType.toLowerCase().equals("ascii") ||transType.toLowerCase().equals("binary")))
{
closeSocket();
return;
}
if (transTypes.ascii.toLowerCase().equals(transType))
{
sendCommand("TYPE A");
} else
{
sendCommand("TYPE I");
}
if (iReplyCode!=200)
{
closeSocket();
return;
}
this.transType=transType;
}
//传输ftp命令
private void sendCommand(String strCommand) throws IOException
{
buffWrite=new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
buffWrite.write(strCommand+separator);
buffWrite.flush();
readReplay();
}
//读ftp命令
private String readLine() throws IOException{
char readArr[]=new char[buffSize];
buffRead=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true)
{
int iread=buffRead.read(readArr);
strMsg=strMsg+String.valueOf(readArr);
if (iread<readArr.length)
{
break;
}
}
/*
* windows上的ftp有的时候返回2个返回值
* (不知道什么原因,大部分的时候返回一个,在打开新数据链接的时候会出现
* ,比如文件传输的时候,刚发送上传或者下载命令,还没有读写文件流,结果同时返回
* 传输开始和传输已经完成的命令,只有取后面的,要不然再读的话就没有了),取后面的
*
*/
String []msg=strMsg.split(separator);
if (msg.length>2)
{
strMsg=msg[msg.length-2];
}
else{
strMsg=msg[0];
}
return strMsg.trim();
}
//读ftp命令的返回码
private void readReplay() throws IOException{
strMsg="";
strReply=readLine();
iReplyCode=Integer.parseInt(strReply.substring(0,3));
}
//创建一个新链接 在取文件列表和上传下载文件的时候有用
private Socket createDataSendSocket() throws IOException{
sendCommand("PASV");
if (iReplyCode!=227)
{
closeSocket();
throw new IOException("不能进入传输模式!");
}
//倒数第二位*256+最后一位是服务器端口
int pos1=strReply.indexOf('(');
int pos2=strReply.indexOf(')');
String clientIp=strReply.substring(pos1+1,pos2);
String [] cliIp=clientIp.split(",");
clientIp=cliIp[0]+"."+cliIp[1]+"."+cliIp[2]+"."+cliIp[3];
int clientPort=Integer.parseInt(cliIp[4])*256+Integer.parseInt(cliIp[5]);
try{
Socket clientSocket=new Socket(clientIp,clientPort);
return clientSocket;
}catch(Exception e)
{
throw new IOException("不能连接Ftp服务器!");
}
}
//取得ftp当前目录下的文件列表
public String [] getFtpFileList(String strMask) throws Exception{
String [] ftpFileList;
if (!bConnect)
{
connect();
}
Socket clientSocket=createDataSendSocket();
byte buffRead[]=new byte[buffSize];
BufferedInputStream buffinput=new BufferedInputStream(clientSocket.getInputStream());
String strGetMsg="";
sendCommand("NLST "+strMask);
if (!(iReplyCode==125||iReplyCode==150||iReplyCode==226))
{
clientSocket.close();
return null;
}
int iRead=buffinput.read(buffRead);
while (iRead!=-1)
{
strGetMsg=strGetMsg+new String(buffRead,0,iRead);
iRead=buffinput.read(buffRead);
}
buffinput.close();
if (clientSocket.isConnected())
{
clientSocket.close();
}
if (!(iReplyCode==226||iReplyCode==250))
{
readReplay();
if (!(iReplyCode==226||iReplyCode==250))
{
throw new IOException("关闭链接错误!");
}
}
ftpFileList=strGetMsg.split(separator);
return ftpFileList;
}
//上传单个文件 paths 为全路径
public void put(String paths) throws IOException
{
if (!bConnect)
{
connect();
}
File file=new File(paths);
if (!file.exists())
{
throw new IOException("要上传的文件不存在!");
}
String filename=file.getName();
Socket clientSocket=createDataSendSocket();
sendCommand("STOR "+filename);
if(!(iReplyCode==125||iReplyCode==150)) //
{
throw new IOException("处理文件错误!");
}
FileInputStream fis=new FileInputStream(file);
BufferedOutputStream buffout=new BufferedOutputStream(clientSocket.getOutputStream());
byte [] buff=new byte[buffSize];
int iReadByte=fis.read(buff);
while (iReadByte!=-1)
{
buffout.write(buff,0,iReadByte);
iReadByte=fis.read(buff);
}
buffout.flush();
buffout.close();
fis.close();
if (clientSocket.isConnected())
{
clientSocket.close();
}
if (!(iReplyCode==226||iReplyCode==250))
{
readReplay();
if (!(iReplyCode==226||iReplyCode==250))
{
throw new IOException("关闭链接错误!");
}
}
}
//上传文件夹下面的过滤文件
public void put(String strFolder,String strMask){
File file=new File(strFolder);
FilenameFilter filter=new fileFilter(strMask);
String fileList[] =file.list(filter);
for (int i=0;i<=fileList.length-1;i++)
{
try{
put(file.getPath()+"/"+fileList[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
//上传文件夹下面的过滤文件,可以过滤多种文件
public void put(String strFolder,String[] strMask)
{
File file=new File(strFolder);
FilenameFilter filefilter=new fileFilter(strMask);
String fileList[]=file.list(filefilter);
for (int i=0;i<=fileList.length-1;i++)
{
try{
put(file.getPath()+"/"+fileList[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
//从ftp服务器取文件
public void get(String strRemoteFileName,String localFolder,String localFile) throws IOException{
if (!bConnect){
connect();
}
Socket clientSocket=createDataSendSocket();
sendCommand("RETR "+strRemoteFileName);
if (!(iReplyCode==125||iReplyCode==150||iReplyCode==226 ||iReplyCode==250 )){
clientSocket.close();
}
File file=new File(localFolder,localFile);
if (file.exists())
{
file.delete();
}
byte [] buff=new byte[buffSize];
FileOutputStream fio=new FileOutputStream(file);
BufferedInputStream buffinput=new BufferedInputStream(clientSocket.getInputStream());
int iRead=buffinput.read(buff);
while (iRead!=-1)
{
fio.write(buff,0,iRead);
iRead=buffinput.read(buff);
}
fio.flush();
fio.close();
buffinput.close();
clientSocket.close();
if (!(iReplyCode==226||iReplyCode==250))
{
readReplay();
if (!(iReplyCode==226||iReplyCode==250))
{
throw new IOException("关闭链接错误!");
}
}
}
//取ftp目录上所有过滤过的文件到本地文件夹
public void get(String localFolder,String strMask) throws Exception
{
String [] fileLists=getFtpFileList(strMask);
for (int i=0;i<=fileLists.length-1;i++)
{
if (!fileLists[i].equals(""))
get(fileLists[i],localFolder,fileLists[i]);
}
}
//关闭ftp链接
public void DisConnect() throws IOException
{
if (socket!=null)
{
sendCommand("QUIT");
closeSocket();
}
}
//返回ftp服务器上文件大小
public long getFileSize(String filename) throws IOException{
if (!bConnect)
{
connect();
}
long fileSize=0;
sendCommand("SIZE "+filename);
if (iReplyCode==213)
{
fileSize= Long.parseLong(strReply.substring(4));
}
return fileSize;
}
//删除ftp目录上的文件
public void deleFile(String filename) throws IOException
{
if (!bConnect)
{
connect();
}
sendCommand("DELE "+filename);
if (iReplyCode!=250)
{
throw new IOException("删除文件错误!");
}
}
//重命名文件
public void renameFile(String oldFilename,String newFilename) throws IOException
{
if (!bConnect)
{
connect();
}
sendCommand("RNFR "+oldFilename);
if (iReplyCode!=350)
{
throw new IOException("更改文件名错误!");
}
sendCommand("RNTO "+newFilename);
if (iReplyCode!=250)
{
throw new IOException("更改文件名错误!");
}
}
//上传某一个目录下的所有文件 如果要文件过滤的话请用 *.* 类型 如 *.txt
class fileFilter implements FilenameFilter{
private String[] suffixs;
private String suffix;
fileFilter(String[] suffixs)
{
this.suffixs=suffixs;
}
fileFilter(String suffix)
{
this.suffix=suffix;
}
public boolean accept(File dir, String name)
{
int pos=name.indexOf('.');
if (pos==-1)
return false;
String suff=name.toLowerCase().substring(pos+1);
if (suffix!=null)
{
suffix=suffix.toLowerCase();
if (suffix.equals("*.*"))
return true;
return suffix.endsWith(suff);
} else
{
boolean bflag=false;
for (int i=0;i<=suffixs.length-1;i++)
{
if (suffixs[i].equals("*.*"))
{
bflag=true;
break;
}
if (suffixs[i].toLowerCase().endsWith(suff))
{
bflag=true;
break;
}
}
if (bflag)
{
return true;
}
else{
return false;
}
}
}
}
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ftpClient ftp=null;
try{
ftp=new ftpClient("127.0.0.1",21,"lh","```","/");
// ftp=new ftpClient();
// ftp.setHost("127.0.0.1");
// ftp.setPort(21);
// ftp.setUsername("lh");
// ftp.setPassword("```");
// ftp.setPath("/");
// ftp.connect();
ftp.setTransType("ascii");
// ftp.put("C:/学习文档","*.mht");
// ftp.put("c:/LNSACC008_20070521.txt");
// ftp.get("/LNSACC008_20070521.txt","c:/","LNSACC008_20070521.txt");
// String[] lists=ftp.getFtpFileList("*.*");
// for (int i=0;i<=lists.length-1;i++)
// System.out.println(lists[i]);
ftp.get("c:/ftp","*.*");
}catch(Exception e)
{
System.out.println("ftp error");
ftp.DisConnect();
return;
}
ftp.DisConnect();
System.out.println("传输成功");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -