ftpjar包下载
apache的包:commons-net.jar
主要使用到的类:
org.apache.commons.net.ftp.FTPClient;
org.apache.commons.net.ftp.FTPFile;
org.apache.commons.net.ftp.FTPReply;
JDK中也有自带的ftp包:
sun.net.ftp.下有FTP操作类
但sun已经不建议使用了, 建议楼主使用apache的包
⑵ 使用FTPClient下载文件报错解决了吗
Unix环境下用shell脚本调jar包中的程序,FTP读取主机文件,用ftpClient中的方法,下面的方法报错了
FTPFile[] ftpFileArr = ftp.listFiles(remoteCheckDir +
File.separator + checkFileName);
其中remoteCheckDir + File.separator + checkFileName为文件的绝对路径
⑶ FtpClient
当时我用SUN 的FtpClient.get()方法下载文件是有问题的,我推荐你用org.apache.commons.net.ftp.FTPClient下载文件,可以解决中文文件下载问题,你可以去我博客里看看哦:http://hi..com/renliangli/blog/item/6ccb6b3a049d95c9d46225a5.html,文章摘给你吧:
现在就来看下我解决的代码吧,希望对遇到同样问题的人有点帮助。
1)把ftp地址中的文件保存到本地的java类源码:
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class Ftp {
/**
* Description: 从FTP服务器下载文件
* @param ip FTP服务器的ip地址
* @param port FTP服务器端口,默认为:21
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath,String fileName,String localPath) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){
File localFile = new File(localPath+File.separator+ff.getName());
//
OutputStream is = new FileOutputStream(localFile);
//注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。
//原因可能是由于aix系统默认的编码为ISO-8859-1
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), is);
is.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Ftp.downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活码.txt", "C:");
}
}
2)将ftp资源以文件流的方式打开,由用户决定保存在本地何处,程序运行后可以从IE跳出框中打开或者保存的Action代码,利用Struts1写的:
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.mocha.test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DownloadAction extends Action{
/** *//**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws IOException
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException{
OutputStream os=null;
try {
os = response.getOutputStream();
response.reset();
downFile("10.32.166.144", 21, "test", "test", "/flashfxp", "激活码.txt",os,response);
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
os.close();
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
* Description: 从FTP服务器下载文件
* @param ip FTP服务器ip地址
* @param port FTP服务器端口,默认为21
* @param username FTP登录账号
* @param password FTP登录密码
* @param remotePath 附件在FTP服务器上的绝对路径
* @param fileName 要下载的文件名
* @param outputStream 输出流
* @param response
* @return
*/
public static boolean downFile(String ip, int port,String username, String password, String remotePath
,String fileName,OutputStream outputStream,HttpServletResponse response) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(ip, port);
//下面三行代码必须要,而且不能改变编码格式
ftp.setControlEncoding("GBK");
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for(int i = 0; i < fs.length; i++){
FTPFile ff = fs[i];
if(ff.getName().equals(fileName)){
String filename = fileName;
//这个就就是弹出下载对话框的关键代码
response.setHeader("Content-disposition",
"attachment;filename=" +
URLEncoder.encode(filename, "utf-8"));
//将文件保存到输出流outputStream中
ftp.retrieveFile(new String(ff.getName().getBytes("GBK"),"ISO-8859-1"), outputStream);
outputStream.flush();
outputStream.close();
}
}
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
}
差点忘了利用ftpclient要用到的jar包了,呵呵,就这两个了:commons-net-1.4.1.jar、jakarta-oro-2.0.8.jar
对了我用的jdk是1.4的。所以commons-net-1.4.1.jar用了这个版本比较老的。
⑷ entp_ftp-1.0.jar怎么用
通过ApacheFtpServer实现,依赖以下jar包:
commons-net-ftp-2.0.jar
ftpserver-core-1.0.6.jar
log4j-1.2.14.jar
mina-core-2.0.4.jar
slf4j-api-1.5.2.jar
slf4j-log4j12-1.5.2.jar
资源下载地址 http://download.csdn.net/detail/smile3670/8508525
⑸ 对JAVA的两个FTP包进行比较分析
ftp *;
这是一个不被官方支持的 但是放在JDK下面的FTP包 正因为不被支
持 所以没有官方提供API 这是其最大的缺陷之一 最重要由于不是官方支持的
所以文档也是没有的
[url]l[/url]
这里有该包的API
先给一个简单的例子 (例子来源互联网)
)显示FTP服务器上的文件
void ftpList_actionPerformed(ActionEvent e) {
String server=serverEdit getText();//输入的FTP服务器的IP地址
String user=userEdit getText(); file://登/录FTP服务器的用户名
String password=passwordEdit getText();//登录FTP服务器的用户名的口令
String path=pathEdit getText();//FTP服务器上的路径
try {
FtpClient ftpClient=new FtpClient();//创建FtpClient对象
ftpClient openServer(server);//连接FTP服务器
ftpClient login(user password);//登录FTP服务器
if (path length()!= ) ftpClient cd(path);
TelnetInputStream is=ftpClient list();
int c;
while ((c=is read())!= ) {
System out print((char) c);}
is close();
ftpClient closeServer();//退出FTP服务器
} catch (IOException ex) {;}
}
)从FTP服务器上下传一个文件
void getButton_actionPerformed(ActionEvent e) {
String server=serverEdit getText();
String user=userEdit getText();
String password=passwordEdit getText();
String path=pathEdit getText();
String filename=filenameEdit getText();
try {
FtpClient ftpClient=new FtpClient();
ftpClient openServer(server);
ftpClient login(user password);
if (path length()!= ) ftpClient cd(path);
ftpClient binary();
TelnetInputStream is=ftpClient get(filename);
File file_out=new File(filename);
FileOutputStream os=new
FileOutputStream(file_out);
byte[] bytes=new byte[ ];
int c;
while ((c=is read(bytes))!= ) {
os write(bytes c);
}
is close();
os close();
ftpClient closeServer();
} catch (IOException ex) {;}
}
)向FTP服务器上上传一个文件
void putButton_actionPerformed(ActionEvent e) {
String server=serverEdit getText();
String user=userEdit getText();
String password=passwordEdit getText();
String path=pathEdit getText();
String filename=filenameEdit getText();
try {
FtpClient ftpClient=new FtpClient();
ftpClient openServer(server);
ftpClient login(user password);
if (path length()!= ) ftpClient cd(path);
ftpClient binary();
TelnetOutputStream os=ftpClient put(filename);
File file_in=new File(filename);
FileInputStream is=new FileInputStream(file_in);
byte[] bytes=new byte[ ];
int c;
while ((c=is read(bytes))!= ){
os write(bytes c);}
is close();
os close();
ftpClient closeServer();
} catch (IOException ex) {;}
}
}
看了这个例子 应该就能用他写东西了
这个包缺点很多 首先就是不被支持也不被官方推荐使用
其次是这个包功能过于简单 简单到无法区分FTP服务器上的File是文件还是目录 有人说
通过返回的字符串来判断 但是据说FTP在不同系统下返回的东西不大一样 所以如果通过
判断字符串会有不好移植的问题
自己想出了一个办法 通过FtpClient中的cd方法来判断
代码如下
try{
ftp cd(file);//file为当前判断的文件
//如果过了说明file是目录
}
catch(IOException e){
//说明file是文件
}
finally{
ftp cd( );//返回上级目录继续判断下一文件
}
我用这种方法做过尝试 结果是只能判断正确一部分 有些目录仍会被认做文件 不知道
是我的方法有错还是别的什么原因
如果对FTP服务没有过高的要求 使用这个包还是不错的 因为他本身就包含在JDK中 不
存在CLASSPATH的问题 不需要导入外部包 较为方便
ftp *;
这个包在Jakarta Commons Net library里 现在的最高版本是 可以从以下地址
下载
[url] net [/url]
zip
里面包含了打包好的jar API 及全部的class文件
[url] net [/url]
src zip
这里包含一些例子以及全部的代码
给出一个该包的例子
import ftp *;
public static void getDataFiles( String server
String username
String password
String folder
String destinationFolder
Calendar start
Calendar end )
{
try
{
// Connect and logon to FTP Server
FTPClient ftp = new FTPClient();
nnect( server );
ftp login( username password );
System out println( Connected to +
server + );
System out print(ftp getReplyString());
// List the files in the directory
ftp changeWorkingDirectory( folder );
FTPFile[] files = ftp listFiles();
System out println( Number of files in dir: + files length );
DateFormat df = DateFormat getDateInstance( DateFormat SHORT );
for( int i= ; i
{
Date fileDate = files[ i ] getTimestamp() getTime();
if( pareTo( start getTime() ) >= &&
pareTo( end getTime() ) <= )
{
// Download a file from the FTP Server
System out print( df format( files[ i ] getTimestamp() getTime() ) );
System out println( + files[ i ] getName() );
File file = new File( destinationFolder +
File separator + files[ i ] getName() );
FileOutputStream fos = new FileOutputStream( file );
ftp retrieveFile( files[ i ] getName() fos );
fos close();
file setLastModified( fileDate getTime() );
}
}
// Logout from the FTP Server and disconnect
ftp logout();
ftp disconnect();
}
catch( Exception e )
{
e printStackTrace();
}
}
同 ftp相同 都是先建立FtpClient(注意两包的大小写不同)的实例 然后通过
connect()方法连接 login()方法登陆 但是 ftp *明显比sun
net ftp功能强大很多
ftp *包将FTP中的file单独出来成为了一个新类FTPFile 还有
类FTPFileEntryParser parse 没有仔细研究 但是从字面来看应该是转化为某种形势的
类 有待研究
同时这个mons net jar包中也提供了FTP服务器 telnet mail等一系列类库
ftp *包的缺点在于需要设置classpath 并且需要下载jakarta
oro jar这个包才能运行(如果没有这个包 会在ftp listFiles()方法后抛出找不
到class异常) 此包无须在代码中import 只需设置在classpath中即可 下载地址
[url] oro zip[/url]
如果想要强大的FTP服务 那么 ftp *包应该是你的最好选择 而
且也是开源 免费的
这个包的问题是:
使用Jakarta Commons Net library需要在环境变量里面编辑classpath
这是不方便的地方
lishixin/Article/program/Java/hx/201311/27057
⑹ 求每日定时在服务器的FTP上取数据文件的源码(JAVA)
这个是可以向服务器端发送文字的程序,就是在客户端发送一句hello在服务器也可以接受到hello,这个程序可以修改一下就可以了。具体修改方法是增加一个定时器,然后把字符流改成字节流,现在有点忙,你先研究啊,近两天帮你写写看。
服务器端:
import java.net.*;
import java.io.*;
public class DateServer {
public static void main(String[] args) {
ServerSocket server=null;
try{
server=new ServerSocket(6666);
System.out.println(
"Server start on port 6666...");
while(true){
Socket socket=server.accept();
new SocketHandler(socket).start();
/*
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(new java.util.Date().toLocaleString());
out.close();
*/
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(server!=null) {
try{
server.close();
}catch(Exception ex){}
}
}
}
}
class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket=socket;
}
public void run() {
try{
PrintWriter out=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()
)
);
out.println(
new java.util.Date().
toLocaleString());
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
客户端:
package com.briup;
import java.io.*;
import java.net.*;
public class FtpClient {
public static void main(String[] args) {
if(args.length==0) {
System.out.println("Usage:java FtpClient file_path");
System.exit(0);
}
File file=new File(args[0]);
if(!file.exists()||!file.canRead()) {
System.out.println(args[0]+" doesn't exist or can not read.");
System.exit(0);
}
Socket socket=null;
try{
socket=new Socket(args[1],Integer.parseInt(args[2]));
BufferedInputStream in=new BufferedInputStream(
new FileInputStream(file)
);
BufferedOutputStream out=new BufferedOutputStream(
socket.getOutputStream()
);
byte[] buffer=new byte[1024*8];
int i=-1;
while((i=in.read(buffer))!=-1) {
out.write(buffer,0,i);
}
System.out.println(socket.getInetAddress().getHostAddress()+" send file over.");
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}finally{
if(socket!=null) {
try{
socket.close();
}catch(Exception ex){}
}
}
}
}
⑺ java 下载异地FTP中的zip文件
好像需要一个支持jar包把,把ftp4j的下载地址贴出来
⑻ java中怎么实现ftp文件传输
packagecom.quantongfu.ftp.ftp;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.util.List;
importorg.apache.commons.net.ftp.FTPReply;
importorg.apache.log4j.Logger;
importorg.apache.log4j.net.SocketServer;
importcom.quantongfu.conf.FtpConf;
/**
*@项目名称:telinSyslog
*@文件名称:Ftp.java
*@创建日期:2015年9月14日下午3:22:08
*@功能描述:ftp实体类,用于连接,上传
*@修订记录:
*/
publicclassFtp{
privatestaticLoggerlogger=Logger.getLogger(Ftp.class);
privateFTPClientftp;
/**
*
*@parampath
*上传到ftp服务器哪个路径下
*@paramaddr
*地址
*@paramport
*端口号
*@paramusername
*用户名
*@parampassword
*密码
*@return
*@throwsException
*/
publicbooleanconnect()throwsException{
booleanresult=false;
ftp=newFTPClient();
intreply;
ftp.connect(FtpConf.FTP_HOST,FtpConf.FTP_PORT);
ftp.login(FtpConf.FTP_USER_NAME,FtpConf.FTP_PASSWORD);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.setDataTimeout(60000);
reply=ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
returnresult;
}
if(FtpConf.IS_FTP_DIRECTORY){
ftp.changeWorkingDirectory(FtpConf.FTP_DIRECTORY);
}
result=true;
returnresult;
}
/**
*
*@paramfiles
*上传的文件
*@throwsException
*/
publicbooleanupload(Filefile)throwsIOException{
FileInputStreaminput=null;
try{
input=newFileInputStream(file);
booleanb=ftp.storeFile(file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
}
returnb;
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}finally{
if(input!=null){
input.close();
}
}
}
/**
*
*@paramfiles
*上传的文件
*@throwsException
*/
publicbooleanupload(ServerSocketserver,Filefile)throwsException{
FileInputStreaminput=null;
try{
if(!file.exists()){
returntrue;
}
input=newFileInputStream(file);
booleanb=ftp.storeFile(server,file.getName()+".tmp",input);
if(b){
b=ftp.rename(file.getName()+".tmp",file.getName());
if(b){
file.delete();
}
}
returnb;
}catch(Exceptione){
logger.error("ftperror"+e.getMessage());
returnfalse;
}finally{
if(input!=null){
try{
input.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/*断开连接*/
publicvoiddisConnect(){
try{
if(ftp!=null){
ftp.disconnect();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
/*获取连接*/
publicstaticFtpgetFtp(){
Ftpftp=newFtp();
try{
ftp.connect();
}catch(Exceptione){
logger.error("FTP连接异常"+e.getMessage());
e.printStackTrace();
}
returnftp;
}
/*重连*/
publicFtpreconnect(){
disConnect();
returngetFtp();
}
}
使用Apache FtpClient jar包,获取jar : http://commons.apache.org/net/
⑼ 用java实现FTP需要导入什么包,导入哪里呢,能不能改个包
com.jcraft.jsch_0.1.31.jar,commons-net-3.2.jar。这是我实现FTP上传使用的jar,希望对你有用。