什么是FTP
ftp是文件傳輸協(xié)議瑞驱,用于在網絡上傳輸文件的協(xié)議,可以簡單理解為ftp是一個服務器浸间,我們可以把文件上傳到ftp服務上恨憎,也可以從ftp上下載文件
在本機上搭建一個ftp服務(這里以win7系統(tǒng)為例)
-
首先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服務
打開瀏覽器猎贴,輸入網址ftp://192.168.119.80班缎,這個ip是你本機的ip
image.png
你可以在剛剛的物理路徑下放一個文件蝴光,搭建成功
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虱疏,F(xiàn)tpUtil這個類中有各種方法,一看就能懂
附上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;
}
/**
* ?????????????????????????????????б?
*
* @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??????
*/
}
/*????????*/
}