什么是FTP
ftp是文件传输协议,用于在网络上传输文件的协议,可以简单理解为ftp是一个服务器,我们可以把文件上传到ftp服务上,也可以从ftp上下载文件
在本机上搭建一个ftp服务(这里以win7系统为例)
-
首先win+R,输入optionalfeatures
image.png -
找到Internet信息服务,将FTP服务器和web管理工具选中,其子目录也要选中
image.png -
然后点击确定,会看到IIS服务正在安装,让你等几分钟
安装完之后,右键我的电脑,管理,左侧菜单最下边,服务和应用程序,展开,Internet信息服务
image.png -
在“网站”文件夹右键添加ftp站点
image.png -
添加站点名称和物理路径,物理路径自己随便新建个文件夹就行,下一步
image.png -
Ip地址选择自己电脑的ip,SSL选择允许,ftp服务的默认端口为21,下一步
image.png -
身份验证选 “基本”,访问权限“所有用户”,可读可写
image.png - 点击完成,你会在网站的文件夹下看到你刚刚新建的站点
验证一下我们搭建的ftp服务
image.png打开浏览器,输入网址ftp://192.168.119.80,这个ip是你本机的ip
你可以在刚刚的物理路径下放一个文件,搭建成功
ftp搭建好之后,我们来用Java代码连接到ftp并上传一个文件
直接上代码:
FtpUtil ftpclient= new FtpUtil(ip,port,username,password);
try {
ftpclient.connectServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new AppException("登录FTP出错!");
}
try {
ftpclient.uploadFileByContent(fileName, data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new AppException("上传文件失败!");
}
注意:这里上传的是具有txt文本内容的String类型的字符串data,而不是文本类型file,FtpUtil这个类中有各种方法,一看就能懂
附上FtpUtil.java代码
package com.neusoft.si.simis.local.treatment.payment;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
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;
}
/**
* upload �ϴ��ļ�
*
* @param filename
* Ҫ�ϴ����ļ���
* @param newname
* �ϴ�������ļ���
* @return -1 �ļ������� >=0 �ɹ��ϴ��������ļ��Ĵ�С
* @throws Exception
*/
public long uploadFileByContent(String filename, String Content) throws Exception {
long result = 0;
TelnetOutputStream os = null;
try {
os = ftpClient.put(filename);
result = Content.length();
byte[] bytes = Content.getBytes();
int c=bytes.length;
os.write(bytes, 0,c );
} finally {
if (os != null) {
os.close();
}
}
return result;
}
/**
* ��ftp�����ļ�������
*
* @param filename
* �������ϵ��ļ���
* @param newfilename
* ������ɵ��ļ���
* @return
* @throws Exception
*/
public InputStream downloadFile(String filename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
InputStream downloadis = 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) {
swapStream.write(bytes, 0, c);
//result = result + c;
}
byte[] swapByteArray = swapStream.toByteArray();
downloadis= new ByteArrayInputStream(swapByteArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return downloadis;
}
/**
* ȡ������ڵ�ǰ����Ŀ¼��ij��Ŀ¼�������ļ��б�
*
* @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;
}
/**
*
* <p>ɾ��ftp�ϵ��ļ�</p>
* @author newname 2012-12-26
* @param srcFname
* @return true || false
*/
public boolean removeFile(String filename) throws Exception {
boolean flag = false;
if( ftpClient!=null ){
try {
// ftpClient.cd(url);
ftpClient.sendServer("DELE "+filename+"\r\n");
int status=ftpClient.readServerResponse();
if(status==250 || status==226){
flag=true;
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return flag;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
return flag;
}
}
}
return flag;
}
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ɾ���ļ�
*/
}
/*��˰�ӿڴ��*/
}
网友评论