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

javaftp文件上传

发布时间: 2022-11-13 19:34:41

‘壹’ 怎么用java实现ftp上传

sun.net.ftp.FtpClient.,该类库主要提供了用于建立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服务器的连接,使用默认端口号。
public void openServer(String host,int port)
这个方法用于建立一条与指定主机、指定端口上的FTP服务器的连接。
打开连接之后,接下来的工作是注册到FTP服务器。这时需要利用下面的方法。
public void login(String username,String password)
此方法利用参数username和password登录到FTP服务器。使用过Intemet的用户应该知道,匿名FTP服务器的登录用户名为anonymous,密码一般用自己的电子邮件地址。
下面是FtpClient类所提供的一些控制命令。
public void cd(String remoteDirectory):该命令用于把远程系统上的目录切换到参数remoteDirectory所指定的目录。
public void cdUp():该命令用于把远程系统上的目录切换到上一级目录。
public String pwd():该命令可显示远程系统上的目录状态。
public void binary():该命令可把传输格式设置为二进制格式。
public void ascii():该命令可把传输协议设置为ASCII码格式。
public void rename(String string,String string1):该命令可对远程系统上的目录或者文件进行重命名操作。
除了上述方法外,类FtpClient还提供了可用于传递并检索目录清单和文件的若干方法。这些方法返回的是可供读或写的输入、输出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回与远程机器上当前目录相对应的输入流。
public TelnetInputStream get(String filename)
获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
public TelnetOutputStream put(String filename)
以写方式打开一输出流,通过这一输出流把文件filename传送到远程计算机

package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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;

/**
* ftp上传,下载

*
* @author why 2009-07-30
*
*/
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;
}
/**
* 从ftp下载文件到本地
*
* @param filename
* 服务器上的文件名
* @param newfilename
* 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = 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) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相对于当前连接目录的某个目录下所有文件列表
*
* @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;
}
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删除文件
*/
}
}

‘贰’ 救火,如何用JAVA实现FTP多文件上传

新建一个web工程,用来测试上传功能。搭建好从前台访问后台的整个框架,并测试是否能接受参数。从apache官网上下载jar包,这里我们需要的jar包共三个,从官网或者其他途径都可以下载得到。编写上传的工具类。工具类主要是涉及两个方法,首先是连接服务器的方法。和我们平常常用的连接数据库等的方法类似,需要有服务器名,用户名和密码。第二个主要的方法就是上传的方法,上传的方法接受一个文件,这里需要注意的,需要去判断传入的是一个文件还是一个文件夹,如果是文件夹,需要循环进行文件上传处理。写方法调用工具类里的方法,并测试上传功能。这里需要注意的是连接服务器的端口号,20表示连接服务器,21表示有上传操作。

‘叁’ 北大青鸟java培训:用PHP控制FTP文件上传

利用PHP,你总是可以有多种方式来完成某个特定的任务。
我们就拿文件上传举个例子。
当然了,你可以按照传统的方式来使用HTTP文件上传,把文件直接传输到Web服务器磁盘上。
河南电脑培训http://www.kmbdqn.cn/认为你还可以用更加奇异的方式上传,用FTP协议两步就完成上传:从你的本地硬盘到Web服务器,然后再到FTP服务器。
PHP在本机同时支持FTP和HTTP上传,所以你可以根据自己应用程序的设计需要进行最佳的选择。
使用PHP的FTP函数进行文件传输几乎与使用传统的FTP客户端相同——你会看到连函数的名字都和标准的FTP命令类似。
关于HTTP文件上传的文章已经多得满天飞了,这就是为什么本文有必要把注意力放在基于FTP的文件上传上了(但是在后面给出的例子中,两种方式你都会看到)。
要注意的是,本教程假设你已经安装好了PHP/Apache,而且HTTP文件上传和FTP的函数都已经激活了。
第一步:确信你拥有连接/上传到FTP服务器的权限PHP的FTP函数需要客户端-服务器连接,所以你需要在进行文件上传之前登录到目标服务器上。
你的第一项任务是确信你已经拥有了完成这项任务的信任书。
这一步可能看起来是理所当然的,但是你会惊奇地发现有多少开发人员忘了这么做,结果后来浪费大量的时间来解决因此而出现的问题。

‘肆’ 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();
}
}

‘伍’ java ftp上传不了文件怎么办

准备条件:java实现ftp上传用到了commons-net-3.3.jar包
首先建立ftphost连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

public boolean connect(String path, String addr, int port, String username, String password) {
try {
//FTPClient ftp = new FTPHTTPClient(addr, port, username, password);
ftp = new FTPClient();
int reply;
ftp.connect(addr);
System.out.println("连接到:" + addr + ":" + port);
System.out.print(ftp.getReplyString());
reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
System.err.println("FTP目标服务器积极拒绝.");
System.exit(1);
return false;
}else{
ftp.login(username, password);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(path);
System.out.println("已连接:" + addr + ":" + port);
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
return false;
}

‘陆’ java如何实现将FTP文件转移到另一个FTP服务器上

你有FTPClient就比较好办,假如你的两台FTP服务器分别为fs1和fs2

在本地开发代码思路如下:

  1. 通过FTPClient连接上fs1,然后下载(可以循环批量下载)到本地服务器,保存到一个临时目录。

  2. 下载完成后,FTPClient断开与fs1的连接,记得必须logout。

  3. 本地服务器通过FileInputStream将刚下载到临时目录的文件读进来,得到一个List<File>集合。

  4. 通过FTPClient连接上fs2,循环List<File>集合,将文件上传至fs2的特定目录,然后清空临时目录,上传完毕后,断开fs2的连接,同样必须logout。

‘柒’ java ftp 上传文件失败

首先确认ftp服务器是否支持Passive模式,其次看看是否防火墙或网络链路问题
建议抓包看看

‘捌’ 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);
}

}
}

‘玖’ 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);*/
}
}

‘拾’ java ftp上传文件夹及子目录文件时,只能上传部分文件 急!

ftp上传我不知道··
如果是文件上传到服务器的话希望这代码能起到一定的作用·
在servlet里面写:
// 保存文件到服务器中
String fileName = null;
try {
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField()) {
fileName = item.getName();
try {
item.write(new File(uploadPath + fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println("保存文件到服务器失败");
errorElement.setText(ErrorCode.VVLIVE_UPLOADFILD + "");
}

热点内容
fpga编程语言 发布:2024-10-06 10:29:24 浏览:341
python按时间排序 发布:2024-10-06 10:02:50 浏览:214
安卓收款机下载什么应用能收款 发布:2024-10-06 09:38:29 浏览:1000
java初级工程师面试题 发布:2024-10-06 09:37:49 浏览:217
知鸟在哪里修改密码 发布:2024-10-06 09:37:10 浏览:303
怎么更改微信钱包密码 发布:2024-10-06 09:28:08 浏览:549
控制中心不支持配置怎么办 发布:2024-10-06 09:16:39 浏览:811
地暖存储罐 发布:2024-10-06 09:10:19 浏览:580
搭建模型服务器 发布:2024-10-06 09:05:23 浏览:845
java使用类 发布:2024-10-06 09:05:22 浏览:931