<div class="article_manage clearfix">
<div class="article_l">
<span class="link_categories">
标签:
<a href="http://www.csdn.net/tag/ftp%e6%9c%8d%e5%8a%a1%e5%99%a8" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">ftp服务器</a><a href="http://www.csdn.net/tag/java" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">java</a><a href="http://www.csdn.net/tag/%e9%80%9a%e4%bf%a1" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">通信</a><a href="http://www.csdn.net/tag/Socket%e7%bc%96%e7%a8%8b" target="_blank" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_tag']);">Socket编程</a>
</span>
</div>
<div class="article_r">
<span class="link_postdate">2015-11-12 17:46</span>
<span class="link_view" title="阅读次数">3380人阅读</span>
<span class="link_comments" title="评论次数"> <a href="#comments" onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_pinglun'])">评论</a>(0)</span>
<span class="link_collect tracking-ad" data-mod="popu_171"> <a href="javascript:void(0);" onclick="javascript:collectArticle('Java%e8%bf%9e%e6%8e%a5FTP%e6%9c%8d%e5%8a%a1%e5%99%a8%e5%b9%b6%e4%b8%94%e5%ae%9e%e7%8e%b0%e5%af%b9%e5%85%b6%e6%96%87%e4%bb%b6%e7%9a%84%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd','49777467');return false;" title="收藏" target="_blank">收藏</a></span>
<span class="link_report"> <a href="#report" onclick="javascript:report(49777467,2);return false;" title="举报">举报</a></span>
</div>
</div>
<div class="embody" style="display:none" id="embody">
<span class="embody_t">本文章已收录于:</span>
<div class="embody_c" id="lib" value="{"err":0,"msg":"ok","data":[]}"></div>
</div>
<style type="text/css">
.embody{
padding:10px 10px 10px;
margin:0 -20px;
border-bottom:solid 1px #ededed;
}
.embody_b{
margin:0 ;
padding:10px 0;
}
.embody .embody_t,.embody .embody_c{
display: inline-block;
margin-right:10px;
}
.embody_t{
font-size: 12px;
color:#999;
}
.embody_c{
font-size: 12px;
}
.embody_c img,.embody_c em{
display: inline-block;
vertical-align: middle;
}
.embody_c img{
width:30px;
height:30px;
}
.embody_c em{
margin: 0 20px 0 10px;
color:#333;
font-style: normal;
}
</style>
<script type="text/javascript">
$(function () {
try
{
var lib = eval("("+$("#lib").attr("value")+")");
var html = "";
if (lib.err == 0) {
$.each(lib.data, function (i) {
var obj = lib.data[i];
//html += '<img src="' + obj.logo + '"/>' + obj.name + " ";
html += ' <a href="' + obj.url + '" target="_blank">';
html += ' <img src="' + obj.logo + '">';
html += ' <em><b>' + obj.name + '</b></em>';
html += ' </a>';
});
if (html != "") {
setTimeout(function () {
$("#lib").html(html);
$("#embody").show();
}, 100);
}
}
} catch (err)
{ }
});
</script>
<div class="category clearfix">
<div class="category_l">
<img src="http://static.blog.csdn.net/images/category_icon.jpg">
<span>分类:</span>
</div>
<div class="category_r">
<label onclick="GetCategoryArticles('5943343','u013761665','top','49777467');">
<span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">Socket编程<em>(2)</em></span>
<img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
<img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
<div class="subItem">
<div class="subItem_t"><a href="http://blog.csdn.net/u013761665/article/category/5943343" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
<ul class="subItem_l" id="top_5943343">
</ul>
</div>
</label>
<label onclick="GetCategoryArticles('1924011','u013761665','top','49777467');">
<span onclick="_gaq.push(['_trackEvent','function', 'onclick', 'blog_articles_fenlei']);">Thinking In Java<em>(36)</em></span>
<img class="arrow-down" src="http://static.blog.csdn.net/images/arrow_triangle _down.jpg" style="display:inline;">
<img class="arrow-up" src="http://static.blog.csdn.net/images/arrow_triangle_up.jpg" style="display:none;">
<div class="subItem">
<div class="subItem_t"><a href="http://blog.csdn.net/u013761665/article/category/1924011" target="_blank">作者同类文章</a><i class="J_close">X</i></div>
<ul class="subItem_l" id="top_1924011">
</ul>
</div>
</label>
</div>
</div>
<script type="text/javascript" src="http://static.blog.csdn.net/scripts/category.js"></script>
<div class="bog_copyright">
<p class="copyright_p">版权声明:本文为博主原创文章,未经博主允许不得转载。</p>
</div>
概述
FTP是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。FTP作为网络共享文件的传输协议,在网络应用软件中具有广泛的应用。FTP的目标是提高文件的共享性和可靠高效地传送数据。在FTP的使用当中,用户经常遇到两个概念:”下载”(Download)和”上传”(Upload)。本文就主要针对这两个操作来进行说明(当然,也包括FTP服务器的连接和登录等操作)。
本文链接:http://blog.csdn.net/lemon_tree12138/article/details/49777467 – Coding-Naga
–转载请注明出处
笔者环境
系统环境:Windows 7(客户端与服务器均是)
服务器:自建FTP服务器(关于FTP服务器的搭建,本文不作说明。网上都有.)
开发环境:Jdk 1.8
引入第三方库:commons-net-2.2.jar(针对第一种方法)
一、基于第三方库FtpClient的FTP服务器数据传输
由于是基于第三方库,所以这里基本上没有太多要说明的东西。就是导入第三方库再调用即可,调用过程从下面的代码可以参见。为了便于文章的完整性,这也是给出其程序结构图吧。
图-1 基于FtpClient的FTP网络文件传输图
1.FTP的连接及登录
- public static FtpClient connectFTP(String url, int port, String username, String password) {
- //创建ftp
- FtpClient ftp = null;
- try {
- //创建地址
- SocketAddress addr = new InetSocketAddress(url, port);
- //连接
- ftp = FtpClient.create();
- ftp.connect(addr);
- //登陆
- ftp.login(username, password.toCharArray());
- ftp.setBinaryType();
- } catch (FtpProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return ftp;
- }
public static FtpClient connectFTP(String url, int port, String username, String password) {
//创建ftp
FtpClient ftp = null;
try {
//创建地址
SocketAddress addr = new InetSocketAddress(url, port);
//连接
ftp = FtpClient.create();
ftp.connect(addr);
//登陆
ftp.login(username, password.toCharArray());
ftp.setBinaryType();
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ftp;
}
2.上传文件到FTP服务器
- public static void upload(String localFile, String ftpFile, FtpClient ftp) {
- OutputStream os = null;
- FileInputStream fis = null;
- try {
- // 将ftp文件加入输出流中。输出到ftp上
- os = ftp.putFileStream(ftpFile);
- File file = new File(localFile);
- // 创建一个缓冲区
- fis = new FileInputStream(file);
- byte[] bytes = new byte[1024];
- int c;
- while((c = fis.read(bytes)) != -1){
- os.write(bytes, 0, c);
- }
- System.out.println(”upload success!!”);
- } catch (FtpProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if(os!=null) {
- os.close();
- }
- if(fis!=null) {
- fis.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
public static void upload(String localFile, String ftpFile, FtpClient ftp) {
OutputStream os = null;
FileInputStream fis = null;
try {
// 将ftp文件加入输出流中。输出到ftp上
os = ftp.putFileStream(ftpFile);
File file = new File(localFile);
// 创建一个缓冲区
fis = new FileInputStream(file);
byte[] bytes = new byte[1024];
int c;
while((c = fis.read(bytes)) != -1){
os.write(bytes, 0, c);
}
System.out.println("upload success!!");
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os!=null) {
os.close();
}
if(fis!=null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.从FTP服务器下载文件
- public static void download(String localFile, String ftpFile, FtpClient ftp) {
- InputStream is = null;
- FileOutputStream fos = null;
- try {
- // 获取ftp上的文件
- is = ftp.getFileStream(ftpFile);
- File file = new File(localFile);
- byte[] bytes = new byte[1024];
- int i;
- fos = new FileOutputStream(file);
- while((i = is.read(bytes)) != -1){
- fos.write(bytes, 0, i);
- }
- System.out.println(”download success!!”);
- } catch (FtpProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if(fos!=null) {
- fos.close();
- }
- if(is!=null){
- is.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
public static void download(String localFile, String ftpFile, FtpClient ftp) {
InputStream is = null;
FileOutputStream fos = null;
try {
// 获取ftp上的文件
is = ftp.getFileStream(ftpFile);
File file = new File(localFile);
byte[] bytes = new byte[1024];
int i;
fos = new FileOutputStream(file);
while((i = is.read(bytes)) != -1){
fos.write(bytes, 0, i);
}
System.out.println("download success!!");
} catch (FtpProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fos!=null) {
fos.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、基于Socket的FTP服务器数据传输
其实上面的基于第三方包FtpClient的方法中,原理层也是基于Socket来进行通信的。所以,我们当然也可以使用Socket直接来写这个FtpClient的代码。下面给出基于Socket通信的结构构架图。这里有一点需要大家注意一下,我们的FTP协议中有两个端口(20和21)。通常情况下,我们的21号端口就是平时大家口口相传的是FTP服务器的端口号,不过其实它只是FTP服务器中的命令端口号。它是负责传送命令给FTP,一些操作如“登录”、“改变目录”、“删除文件”,依靠这个连接发送命令就可完成。而对于20号端口号(也有可能是其它的一些端口号),对于有数据传输的操作,主要是显示目录列表,上传、下载文件,我们需要依靠另一个Socket来完成。
所以在下面的结构图中,我们可以看到我们有重新获得端口号的过程,正是这个原因。
图-2 基于Socket的FTP网络文件传输图
1.FTP连接
- public void connectFtp() {
- try {
- mFtpClient = new Socket(Config.FTP.HOST_IP, Config.FTP.HOST_PORT);
- mReader = new BufferedReader(new InputStreamReader(mFtpClient.getInputStream()));
- mWriter = new BufferedWriter(new OutputStreamWriter(mFtpClient.getOutputStream()));
- sendCommand(”USER ” + Config.FTP.FTP_USERNAME);
- sendCommand(”PASS ” + Config.FTP.FTP_PASSWD);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
public void connectFtp() {
try {
mFtpClient = new Socket(Config.FTP.HOST_IP, Config.FTP.HOST_PORT);
mReader = new BufferedReader(new InputStreamReader(mFtpClient.getInputStream()));
mWriter = new BufferedWriter(new OutputStreamWriter(mFtpClient.getOutputStream()));
sendCommand("USER " + Config.FTP.FTP_USERNAME);
sendCommand("PASS " + Config.FTP.FTP_PASSWD);
} catch (IOException e) {
e.printStackTrace();
}
}
2.向FTP服务器发送命令
- private void sendCommand(String command) throws IOException {
- if (Tools.StringTools.isEmpty(command)) {
- return;
- }
- if (mFtpClient == null) {
- return;
- }
- mWriter.write(command + ”\r\n”);
- mWriter.flush();
- }
private void sendCommand(String command) throws IOException {
if (Tools.StringTools.isEmpty(command)) {
return;
}
if (mFtpClient == null) {
return;
}
mWriter.write(command + "\r\n");
mWriter.flush();
}
3.向FTP服务器上传文件
- public void uploadFile(String localPath, String ftpPath) throws IOException {
- // 进入被动模式
- sendCommand(”PASV”);
- // 获得ip和端口
- String response = readNewMessage();
- String[] ipPort = getIPPort(response);
- String ip = ipPort[0];
- int port = Integer.parseInt(ipPort[1]);
- // 建立数据端口的连接
- Socket dataSocket = new Socket(ip, port);
- sendCommand(”STOR ” + ftpPath);
- // 上传文件前的准备
- File localFile = new File(localPath);
- OutputStream outputStream = dataSocket.getOutputStream();
- FileInputStream fileInputStream = new FileInputStream(localFile);
- // 上传文件
- int offset;
- byte[] bytes = new byte[1024];
- while ((offset = fileInputStream.read(bytes)) != -1) {
- outputStream.write(bytes, 0, offset);
- }
- System.out.println(”upload success!!”);
- // 上传文件后的善后工作
- outputStream.close();
- fileInputStream.close();
- dataSocket.close();
- }
public void uploadFile(String localPath, String ftpPath) throws IOException {
// 进入被动模式
sendCommand("PASV");
// 获得ip和端口
String response = readNewMessage();
String[] ipPort = getIPPort(response);
String ip = ipPort[0];
int port = Integer.parseInt(ipPort[1]);
// 建立数据端口的连接
Socket dataSocket = new Socket(ip, port);
sendCommand("STOR " + ftpPath);
// 上传文件前的准备
File localFile = new File(localPath);
OutputStream outputStream = dataSocket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(localFile);
// 上传文件
int offset;
byte[] bytes = new byte[1024];
while ((offset = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, offset);
}
System.out.println("upload success!!");
// 上传文件后的善后工作
outputStream.close();
fileInputStream.close();
dataSocket.close();
}
4.从FTP服务器下载文件
- public void downloadFile(String localPath, String ftpPath) throws IOException {
- // 进入被动模式
- sendCommand(”PASV”);
- // 获得ip和端口
- String response = readNewMessage();
- String[] ipPort = getIPPort(response);
- String ip = ipPort[0];
- int port = Integer.parseInt(ipPort[1]);
- // 建立数据端口的连接
- Socket dataSocket = new Socket(ip, port);
- sendCommand(”RETR ” + ftpPath);
- // 下载文件前的准备
- File localFile = new File(localPath);
- InputStream inputStream = dataSocket.getInputStream();
- FileOutputStream fileOutputStream = new FileOutputStream(localFile);
- // 下载文件
- int offset;
- byte[] bytes = new byte[1024];
- while ((offset = inputStream.read(bytes)) != -1) {
- fileOutputStream.write(bytes, 0, offset);
- }
- System.out.println(”download success!!”);
- // 下载文件后的善后工作
- inputStream.close();
- fileOutputStream.close();
- dataSocket.close();
- }
public void downloadFile(String localPath, String ftpPath) throws IOException {
// 进入被动模式
sendCommand("PASV");
// 获得ip和端口
String response = readNewMessage();
String[] ipPort = getIPPort(response);
String ip = ipPort[0];
int port = Integer.parseInt(ipPort[1]);
// 建立数据端口的连接
Socket dataSocket = new Socket(ip, port);
sendCommand("RETR " + ftpPath);
// 下载文件前的准备
File localFile = new File(localPath);
InputStream inputStream = dataSocket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(localFile);
// 下载文件
int offset;
byte[] bytes = new byte[1024];
while ((offset = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, offset);
}
System.out.println("download success!!");
// 下载文件后的善后工作
inputStream.close();
fileOutputStream.close();
dataSocket.close();
}
5.断开FTP服务器连接
- public void disconnectFtp() {
- if (mFtpClient == null) {
- return;
- }
- if (!mFtpClient.isConnected()) {
- return;
- }
- try {
- mFtpClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
public void disconnectFtp() {
if (mFtpClient == null) {
return;
}
if (!mFtpClient.isConnected()) {
return;
}
try {
mFtpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
本文参考:
http://www.ibm.com/developerworks/cn/linux/l-cn-socketftp/
源码下载:
<div id="digg" articleid="49777467">
<dl id="btnDigg" class="digg digg_enable" onclick="btndigga();">
<dt>顶</dt>
<dd>2</dd>
</dl>
<dl id="btnBury" class="digg digg_enable" onclick="btnburya();">
<dt>踩</dt>
<dd>0</dd>
</dl>
</div>
<div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank"> </a> </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank"> </a></div>
<script type="text/javascript">
function btndigga() {
$(".tracking-ad[data-mod='popu_222'] a").click();
}
function btnburya() {
$(".tracking-ad[data-mod='popu_223'] a").click();
}
</script>
<div style="clear:both; height:10px;"></div>
<div class="similar_article" style="">
<h4>我的同类文章</h4>
<div class="similar_c" style="margin:20px 0px 0px 0px">
<div class="similar_c_t">
<label class="similar_cur">
<span style="cursor:pointer" onclick="GetCategoryArticles('5943343','u013761665','foot','49777467');">Socket编程<em>(2)</em></span>
</label>
<label class="">
<span style="cursor:pointer" onclick="GetCategoryArticles('1924011','u013761665','foot','49777467');">Thinking In Java<em>(36)</em></span>
</label>
</div>
<div class="similar_wrap tracking-ad" data-mod="popu_141" style="max-height:195px;">
<a href="http://blog.csdn.net" style="display:none" target="_blank">http://blog.csdn.net</a>
<ul class="similar_list fl"><li><em>•</em><a href="http://blog.csdn.net/u013761665/article/details/45045735" id="foot_aritcle_45045735undefined6425839364099051" target="_blank" title="Python服务器与多种客户端(Python/Java/Android)之间的通信">Python服务器与多种客户端(Python/Java/Android)之间的通信</a><span>2015-04-15</span><label><i>阅读</i><b>2339</b></label></li> </ul>
<ul class="similar_list fr"><li><em>•</em><a href="http://blog.csdn.net/u013761665/article/details/38959283" id="foot_aritcle_38959283undefined5230865347590525" target="_blank" title="Android中基于TCP协议的网络通信之使用Socket进行通信">Android中基于TCP协议的网络通信之使用Socket进行通信</a><span>2014-08-31</span><label><i>阅读</i><b>1147</b></label></li> </ul>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
GetCategoryArticles('5943343', 'u013761665','foot','49777467');
});
</script>