当前位置:首页 » 文件管理 » javaftp续传

javaftp续传

发布时间: 2022-05-16 14:53:20

1. java ftpclient怎么传输多个文件

/**
* Description: 向FTP服务器上传文件
* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保([email protected])创建
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param path FTP服务器保存目录
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);//连接FTP服务器
//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);//登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);

input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}<pre></pre>

2. Java ftp 断点续传报错

NoClassDefFoundError
1.未通过编译
2.没有引入jar包

3. java ftp上传5G以上大文件,怎么做

java上传可以使用common-fileupload上传组件的。common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件下面先介绍上传文件到服务器(多文件上传):import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2*1024*1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c:\\windows\\temp");
//开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
Iterator iter = fileItems.iterator();//正则匹配,过滤路径取文件名
String regExp=".+\\\\(.+)$";//过滤掉的文件类型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{//保存上传的文件到指定的目录//在下文中上传文件至数据库时,将对这里改写
item.write(new File("d:\\" + m.group(1))); out.print(name+" "+size+"
");
}
catch(Exception e){
out.println(e);
} }
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}

}
}

4. java 实现ftp上传下载,windows下和linux下游何区别

packagecom.weixin.util;

importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.RandomAccessFile;

importorg.apache.commons.net.PrintCommandListener;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;

importcom.weixin.constant.DownloadStatus;
importcom.weixin.constant.UploadStatus;

/**
*支持断点续传的FTP实用类
*@version0.1实现基本断点上传下载
*@version0.2实现上传下载进度汇报
*@version0.3实现中文目录创建及中文文件创建,添加对于中文的支持
*/
publicclassContinueFTP{
publicFTPClientftpClient=newFTPClient();

publicContinueFTP(){
//设置将过程中使用到的命令输出到控制台
this.ftpClient.addProtocolCommandListener(newPrintCommandListener(newPrintWriter(System.out)));
}

/**
*连接到FTP服务器
*@paramhostname主机名
*@paramport端口
*@paramusername用户名
*@parampassword密码
*@return是否连接成功
*@throwsIOException
*/
publicbooleanconnect(Stringhostname,intport,Stringusername,Stringpassword)throwsIOException{
ftpClient.connect(hostname,port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username,password)){
returntrue;
}
}
disconnect();
returnfalse;
}

/**
*从FTP服务器上下载文件,支持断点续传,上传百分比汇报
*@paramremote远程文件路径
*@paramlocal本地文件路径
*@return上传的状态
*@throwsIOException
*/
publicDownloadStatusdownload(Stringremote,Stringlocal)throwsIOException{
//设置被动模式
ftpClient.enterLocalPassiveMode();
//设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatusresult;

//检查远程文件是否存在
FTPFile[]files=ftpClient.listFiles(newString(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length!=1){
System.out.println("远程文件不存在");
returnDownloadStatus.Remote_File_Noexist;
}

longlRemoteSize=files[0].getSize();
Filef=newFile(local);
//本地存在文件,进行断点下载
if(f.exists()){
longlocalSize=f.length();
//判断本地文件大小是否大于远程文件大小
if(localSize>=lRemoteSize){
System.out.println("本地文件大于远程文件,下载中止");
returnDownloadStatus.Local_Bigger_Remote;
}

//进行断点续传,并记录状态
FileOutputStreamout=newFileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=localSize/step;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下载进度:"+process);
//TODO更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
booleanisDo=ftpClient.completePendingCommand();
if(isDo){
result=DownloadStatus.Download_From_Break_Success;
}else{
result=DownloadStatus.Download_From_Break_Failed;
}
}else{
OutputStreamout=newFileOutputStream(f);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=0;
longlocalSize=0L;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下载进度:"+process);
//TODO更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
booleanupNewStatus=ftpClient.completePendingCommand();
if(upNewStatus){
result=DownloadStatus.Download_New_Success;
}else{
result=DownloadStatus.Download_New_Failed;
}
}
returnresult;
}

/**
*上传文件到FTP服务器,支持断点续传
*@paramlocal本地文件名称,绝对路径
*@paramremote远程文件路径,使用/home/directory1/subdirectory/file.ext按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
*@return上传结果
*@throwsIOException
*/
publicUploadStatusupload(Stringlocal,Stringremote)throwsIOException{
//设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
//设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatusresult;
//对远程目录的处理
StringremoteFileName=remote;
if(remote.contains("/")){
remoteFileName=remote.substring(remote.lastIndexOf("/")+1);
//创建服务器远程目录结构,创建失败直接返回
if(CreateDirecroty(remote,ftpClient)==UploadStatus.Create_Directory_Fail){
returnUploadStatus.Create_Directory_Fail;
}
}

//检查远程是否存在文件
FTPFile[]files=ftpClient.listFiles(newString(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length==1){
longremoteSize=files[0].getSize();
Filef=newFile(local);
longlocalSize=f.length();
if(remoteSize==localSize){
returnUploadStatus.File_Exits;
}elseif(remoteSize>localSize){
returnUploadStatus.Remote_Bigger_Local;
}

//尝试移动文件内读取指针,实现断点续传
result=uploadFile(remoteFileName,f,ftpClient,remoteSize);

//如果断点续传没有成功,则删除服务器上文件,重新上传
if(result==UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
returnUploadStatus.Delete_Remote_Faild;
}
result=uploadFile(remoteFileName,f,ftpClient,0);
}
}else{
result=uploadFile(remoteFileName,newFile(local),ftpClient,0);
}
returnresult;
}
/**
*断开与远程服务器的连接
*@throwsIOException
*/
publicvoiddisconnect()throwsIOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}

/**
*递归创建远程服务器目录
*@paramremote远程服务器文件绝对路径
*@paramftpClientFTPClient对象
*@return目录创建是否成功
*@throwsIOException
*/
(Stringremote,FTPClientftpClient)throwsIOException{
UploadStatusstatus=UploadStatus.Create_Directory_Success;
Stringdirectory=remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(newString(directory.getBytes("GBK"),"iso-8859-1"))){
//如果远程目录不存在,则递归创建远程服务器目录
intstart=0;
intend=0;
if(directory.startsWith("/")){
start=1;
}else{
start=0;
}
end=directory.indexOf("/",start);
while(true){
StringsubDirectory=newString(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else{
System.out.println("创建目录失败");
returnUploadStatus.Create_Directory_Fail;
}
}

start=end+1;
end=directory.indexOf("/",start);

//检查所有目录是否创建完毕
if(end<=start){
break;
}
}
}
returnstatus;
}

/**
*上传文件到服务器,新上传和断点续传
*@paramremoteFile远程文件名,在上传之前已经将服务器工作目录做了改变
*@paramlocalFile本地文件File句柄,绝对路径
*@paramprocessStep需要显示的处理进度步进值
*@paramftpClientFTPClient引用
*@return
*@throwsIOException
*/
publicUploadStatusuploadFile(StringremoteFile,FilelocalFile,FTPClientftpClient,longremoteSize)throwsIOException{
UploadStatusstatus;
//显示进度的上传
longstep=localFile.length()/100;
longprocess=0;
longlocalreadbytes=0L;
RandomAccessFileraf=newRandomAccessFile(localFile,"r");
OutputStreamout=ftpClient.appendFileStream(newString(remoteFile.getBytes("GBK"),"iso-8859-1"));
//断点续传
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process=remoteSize/step;
raf.seek(remoteSize);
localreadbytes=remoteSize;
}
byte[]bytes=newbyte[1024];
intc;
while((c=raf.read(bytes))!=-1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes/step!=process){
process=localreadbytes/step;
System.out.println("上传进度:"+process);
//TODO汇报上传状态
}
}
out.flush();
raf.close();
out.close();
booleanresult=ftpClient.completePendingCommand();
if(remoteSize>0){
status=result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else{
status=result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
returnstatus;
}

publicstaticvoidmain(String[]args){
ContinueFTPmyFtp=newContinueFTP();
try{
System.err.println(myFtp.connect("10.10.6.236",21,"5","jieyan"));
// myFtp.ftpClient.makeDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(newString("爱你等于爱自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\yw.flv","/yw.flv",5));
// System.out.println(myFtp.upload("E:\爱你等于爱自己.mp4","/爱你等于爱自己.mp4"));
//System.out.println(myFtp.download("/爱你等于爱自己.mp4","E:\爱你等于爱自己.mp4"));
myFtp.disconnect();
}catch(IOExceptione){
System.out.println("连接FTP出错:"+e.getMessage());
}
}
}

5. java ftp怎么实现java ftp方式的断点续传

运用类的办法,编程人员能够长途登录到FTP服务器,罗列该服务器上的目录,设置传输协议,以及传送文件。FtpClient类涵 盖了简直一切FTP的功用,FtpClient的实例变量保留了有关树立"署理"的各种信息。下面给出了这些实例变量:

public static boolean useFtpProxy

这个变量用于标明FTP传输过程中是不是运用了一个署理,因此,它实际上是一个符号,此符号若为TRUE,标明运用了一个署理主机。

public static String ftpProxyHost

此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机名。

public static int ftpProxyPort

此变量只要在变量useFtpProxy为TRUE时才有用,用于保留署理主机的端口地址。

FtpClient有三种不同方式的结构函数,如下所示:

1、public FtpClient(String hostname,int port)

此结构函数运用给出的主机名和端口号树立一条FTP衔接。

2、public FtpClient(String hostname)

此结构函数运用给出的主机名树立一条FTP衔接,运用默许端口号。

3、FtpClient()

此结构函数将创立一FtpClient类,但不树立FTP衔接。这时,FTP衔接能够用openServer办法树立。

一旦树立了类FtpClient,就能够用这个类的办法来翻开与FTP服务器的衔接。类ftpClient供给了如下两个可用于翻开与FTP服务器之间的衔接的办法。

public void openServer(String hostname)

这个办法用于树立一条与指定主机上的FTP服务器的衔接,运用默许端口号。

6. 用java有一个ftp路径地址,需要把传送一些数据到ftp中怎样实现

1.使用的FileZillaServer开源,安装过后建立的本地FTP服务器。2.使用的apache上FTP工具包,引用到工程目录中。3.IDE,Eclipse,JDK6上传和目录的实现原理:对每一个层级的目录进行判断,是为目录类型、还是文件类型。如果为目录类型,采用递归调用方法,检查到最底层的目录为止结束。如果为文件类型,则调用上传或者方法对文件进行上传或者操作。贴出代码:(其中有些没有代码,可以看看,还是很有用处的)!

7. java jdk1.6环境下实现 ftp文件上传

通过JDK自带的API实现

package com.cloudpower.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* Java自带的API对FTP的操作
* @Title:Ftp.java
* @author: 周玲斌
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 远程文件名
*/
private String remotefilename;
/**
* FTP客户端
*/
private FtpClient ftpClient;

/**
* 服务器连接
* @param ip 服务器IP
* @param port 服务器端口
* @param user 用户名
* @param password 密码
* @param path 服务器路径
* @author 周玲斌
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******连接服务器的两种方法*******/
//第一种方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二种方法
ftpClient = new FtpClient(ip);

ftpClient.login(user, password);
// 设置成2进制传输
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把远程系统上的目录切换到参数path所指定的目录
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 关闭连接
* @author 周玲斌
* @date 2012-7-11
*/
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/**
* 上传文件
* @param localFile 本地文件
* @param remoteFile 远程文件
* @author 周玲斌
* @date 2012-7-11
*/
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//将远程文件加入输出流中
os = ftpClient.put(this.remotefilename);
//获取本地文件的输入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//创建一个缓冲区
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("upload success");
} catch (IOException ex) {
System.out.println("not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 下载文件
* @param remoteFile 远程文件路径(服务器端)
* @param localFile 本地文件路径(客户端)
* @author 周玲斌
* @date 2012-7-11
*/
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex) {
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String agrs[]) {

String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

Ftp fu = new Ftp();
/*
* 使用默认的端口号、用户名、密码以及根目录连接FTP服务器
*/
fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");

//下载
for (int i = 0; i < filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}

String localfile = "E:\\号码.txt";
String remotefile = "/temp/哈哈.txt";
//上传
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}

8. java 实现ftp上传如何创建文件夹

这个功能我也刚写完,不过我也是得益于同行,现在我也把自己的分享给大家,希望能对大家有所帮助,因为自己的项目不涉及到创建文件夹,也仅作分享,不喜勿喷谢谢!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登录
*@paramhostname主机名
*@paramport端口号
*@paramusername用户名
*@parampassword密码
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主机名
*@paramport端口号
*@paramusername用户名
*@parampassword密码
*@paramfpathftp路径
*@paramlocalpath本地路径
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下载文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*关闭流连接、ftp连接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//设置文件类型为二进制(避免解压缩文件失败)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//开通数据端口传输数据,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("连接FTP失败,用户名或密码错误");
}else{
log.info("FTP连接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登录FTP失败,请检查FTP相关配置信息是否正确",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上传失败");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上传成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切换到当前目录
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下载成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夹是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,请检查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下载/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}

9. 如何用java代码实现ftp文件上传

import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class test {

private FTPClient ftp;
/**
*
* @param path 上传到ftp服务器哪个路径下
* @param addr 地址
* @param port 端口号
* @param username 用户名
* @param password 密码
* @return
* @throws Exception
*/
private boolean connect(String path,String addr,int port,String username,String password) throws Exception {
boolean result = false;
ftp = new FTPClient();
int reply;
ftp.connect(addr,port);
ftp.login(username,password);
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(path);
result = true;
return result;
}
/**
*
* @param file 上传的文件或文件夹
* @throws Exception
*/
private void upload(File file) throws Exception{
if(file.isDirectory()){
ftp.makeDirectory(file.getName());
ftp.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File file1 = new File(file.getPath()+"\\"+files[i] );
if(file1.isDirectory()){
upload(file1);
ftp.changeToParentDirectory();
}else{
File file2 = new File(file.getPath()+"\\"+files[i]);

热点内容
支持编译成机器码的语言 发布:2024-04-27 17:31:59 浏览:745
串口服务器ip限制 发布:2024-04-27 17:30:20 浏览:501
sql编程入门经典 发布:2024-04-27 17:28:52 浏览:282
红木卧室有哪些配置 发布:2024-04-27 17:09:47 浏览:855
中心机编程 发布:2024-04-27 17:00:11 浏览:116
lms滤波算法 发布:2024-04-27 16:55:37 浏览:444
苹果电脑远程桌面连接服务器 发布:2024-04-27 16:53:08 浏览:234
为什么安卓手机没有回响 发布:2024-04-27 16:53:08 浏览:375
搭建邮箱中继服务器 发布:2024-04-27 16:40:42 浏览:198
我的世界的神奇宝可梦服务器 发布:2024-04-27 16:28:28 浏览:589