一,代码片
分享一个Ftp上传下载工具类,废话不多说,直接上代码:
FileUtil.java
package com.standard.commonutil.util;
import com.standard.commonutil.file.WriteFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
import java.net.SocketException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* <pre>
* Ftp上传下载工具类
* 支持gizp压缩
* 注意ftp上路径或文件名不要带中文,否则因为操作系统差异可能会出现乱码
* </pre>
*
*/
public class FtpUtil {
private static final Log log = LogFactory.getLog(FtpUtil.class);
/**
* 临时文件后缀名
*/
private final static String TEMP_FILE_SUFFIX = ".temp";
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* ftp地址
*/
private String server;
/**
* ftp端口号
*/
private int port = 21;
private String encode = "UTF-8";
private final static int BUFFER_SIZE = 1024 * 4;
private FTPClient ftpClient;
public FtpUtil(String server, String username, String password, int port) {
this(server, username, password);
this.port = port;
}
public FtpUtil(String server, String username, String password) {
this.username = username;
this.password = password;
this.server = server;
this.init();
}
private void init() {
}
/**
* <pre>
* 连接FTP服务器
* </pre>
*
* @throws SocketException
* @throws IOException
*/
public void connect() throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
// log.info("系统连接到FTP服务器{" + server + "}成功!!!");
ftpClient.login(username, password);
ftpClient.setControlEncoding("UTF-8");
// 设置被动模式
ftpClient.enterLocalPassiveMode();
// 设置以二进制方式传输
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
}
/**
* <pre>
* ftp上传文本文件
* </pre>
*
* @param name 文件名
* @param text 文件内容
* @param isGzip 是否使用gizp压缩
* @return 成功标识
*/
public boolean upload(String name, String text, boolean isGzip) {
byte[] by = null;
try {
by = text.getBytes(encode);
} catch (Exception ex) {
log.error("获取字符串编码错误", ex);
}
ByteArrayInputStream bi = new ByteArrayInputStream(by);
if (!isGzip) {
return upload(name, bi);
} else {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
GZIPOutputStream go = new GZIPOutputStream(bo);
byte b[] = new byte[BUFFER_SIZE];
int i;
while ((i = bi.read(b)) != -1) {
go.write(b, 0, i);
}
go.finish();
go.close();
InputStream is = new ByteArrayInputStream(bo.toByteArray());
return upload(name, is);
} catch (IOException e) {
log.error("FTP上传文件发生异常.", e);
}
}
return false;
}
public boolean upload(String name, InputStream stream) {
boolean flag = false;
if (ftpClient.isConnected()) {
try {
flag = ftpClient.storeFile(name, stream);
} catch (IOException e) {
flag = false;
log.error("FTP上传文件发生异常.", e);
} finally {
try {
stream.close();
} catch (IOException e) {
log.error("关闭IO流异常", e);
}
}
} else {
log.info("Ftp连接不是活动状态");
}
return flag;
}
/**
* <pre>
* ftp下载文本文件
* </pre>
*
* @param remoteFileName 远程文件名
* @param isGzip 是否使用gzip解压
* @return 下载的字符串
*/
public String download(String remoteFileName, boolean isGzip) {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
boolean tr = ftpClient.retrieveFile(remoteFileName, bo);
if (tr) {
InputStreamReader ir = null;
if (!isGzip) {
ir = new InputStreamReader(new ByteArrayInputStream(bo.toByteArray()), encode);
} else {
ir = new InputStreamReader(new GZIPInputStream(new ByteArrayInputStream(bo.toByteArray())), encode);
}
BufferedReader br = new BufferedReader(ir);
StringWriter sw = new StringWriter();
char[] ch = new char[BUFFER_SIZE];
int i;
while ((i = br.read(ch)) != -1) {
sw.write(ch, 0, i);
}
sw.flush();
sw.close();
br.close();
bo.close();
return sw.toString();
} else {
return null;
}
} catch (IOException e) {
log.error("ftp下载文件失败", e);
throw new RuntimeException("ftp下载文件失败");
}
}
public boolean download(final String remoteFileName, String localPath, String localName) {
if (ftpClient.isConnected()) {
try {
createTempFile(localPath, localName, new WriteFile() {
public boolean write(File f) {
OutputStream stream = null;
try {
stream = new FileOutputStream(f);
boolean tr = ftpClient.retrieveFile(remoteFileName, stream);
return tr;
} catch (IOException e) {
log.error("FTP下载文件发生异常.", e);
return false;
} finally {
try {
stream.close();
} catch (IOException e) {
log.error("关闭IO流异常", e);
}
}
}
});
return true;
} catch (Exception ex) {
log.error("ftp下载文件失败", ex);
}
} else {
log.info("Ftp连接不是活动状态");
}
return false;
}
/**
* <pre>
* 关闭ftp连接
* </pre>
*
* @throws IOException
*/
public void close() throws IOException {
// log.info("关闭ftp链接{" + server + "}");
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
/**
* <pre>
* 更改工作目录
* </pre>
*
* @param path
* @return
* @throws IOException
*/
public boolean changeDirectory(String path) throws IOException {
return ftpClient.changeWorkingDirectory(path);
}
/**
* <pre>
* 创建ftp目录
* </pre>
*
* @param pathName
* @return
* @throws IOException
*/
public boolean createDirectory(String pathName) throws IOException {
return ftpClient.makeDirectory(pathName);
}
/**
* <pre>
* 获取当前目录下的文件列表
* </pre>
*
* @return
* @throws IOException
*/
public String[] getListFiels() throws IOException {
return ftpClient.listNames();
}
public FTPFile[] listFiles() throws IOException {
return ftpClient.listFiles();
}
public boolean deleteFile(String filename) throws IOException {
return ftpClient.deleteFile(filename);
}
public boolean renameFile(String filename, String newPath) throws IOException {
return ftpClient.rename(filename, newPath);
}
/**
* @param fileName
* @return function:从服务器上读取指定的文件
* @throws IOException
*/
public String readFile(String path, String fileName) {
InputStream ins = null;
StringBuilder builder = null;
try {
// 从服务器上读取指定的文件
ftpClient.changeWorkingDirectory(path);
ins = ftpClient.retrieveFileStream(fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
String line;
builder = new StringBuilder(150);
while ((line = reader.readLine()) != null) {
System.out.println(line);
builder.append(line);
}
reader.close();
if (ins != null) {
ins.close();
}
// 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
ftpClient.getReply();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
/**
* <pre>
* 创建新文件
* </pre>
*
* @param fileName 文件名
* @param dir 文件路径
* @return 创建成功的文件
* @throws IOException
*/
public static File createTempFile(String dir, String fileName, WriteFile write) {
File dirs = new File(dir);
// 看文件夹是否存在,如果不存在新建目录
if (!dirs.exists()) {
dirs.mkdirs();
}
File temp = new File(dir + File.separator + fileName + TEMP_FILE_SUFFIX);
boolean isSuccess = write.write(temp);
if (isSuccess) {
File file = new File(dir + File.separator + fileName);
boolean flag = false;
while (!flag) {
flag = temp.renameTo(file);
if (!flag) {
file.delete();
}
}
return file;
} else {
throw new RuntimeException("创建临时文件发生异常");
}
}
}
WriteFile.java
import java.io.File;
public interface WriteFile {
public boolean write(File f);
}
WriteFileImpl.java
package com.standard.commonutil.file;
import com.standard.commonutil.util.StringHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* <pre>
* 写文件
* </pre>
*
*/
public class WriteFileImpl implements WriteFile {
public final Log log = LogFactory.getLog(WriteFileImpl.class);
/**
* 临时文件后缀名
*/
private final static String TEMP_FILE_SUFFIX = ".temp";
private String content;
public WriteFileImpl(String content) {
if (StringHelper.isEmpty(content)) {
this.content = "";
} else {
this.content = content;
}
}
@Override
public boolean write(File file) {
try {
String filePath = file.getAbsolutePath();
if (filePath.contains(TEMP_FILE_SUFFIX)) {
filePath = filePath.substring(0, filePath.indexOf(TEMP_FILE_SUFFIX));
}
File existFile = new File(filePath);
if (existFile.exists() && existFile.isFile()) {
throw new Exception("文件已存在不能重复生成:" + filePath);
}
FileOutputStream fos = new FileOutputStream(file);
Writer out = new OutputStreamWriter(fos, "GBK");
out.write(content);
out.close();
fos.close();
return true;
} catch (Exception e) {
log.error("写入文件{" + file.getName() + "}异常", e);
throw new RuntimeException("生成文件发生异常:" + file.getName(), e);
}
}
}
二,maven依赖
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>1.4.1</version>
<optional>true</optional>
</dependency>
三,最后
拿走不谢,要谢就打赏一下吧,不打赏至少关注一下博主吧,呵呵,哈哈,嘿嘿。