ftp上传
package com.xnh.atom.server;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FtpChinaFileUtil {
private static final Logger log = LoggerFactory.getLogger(FtpChinaFileUtil.class);
private String ip = "";
private String username = "";
private String password = "";
private int port = 21;
private String path = "";
FTPClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
private String LOCAL_CHARSET = "GBK";
public FtpChinaFileUtil(){}
public FtpChinaFileUtil(String path,String serverIP, int port, String username, String password) {
this.path = path;
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 连接ftp服务器
*
* @throws IOException ,FtpProtocolException
*/
public void connectServer() throws IOException {
System.out.println("ftp开始创建:"+ip+","+port);
ftpClient = new FTPClient();
ftpClient.setConnectTimeout(20000);
ftpClient.setDataTimeout(3*60*1000);
ftpClient.setControlKeepAliveReplyTimeout(10000);
ftpClient.setControlKeepAliveTimeout(10000);
ftpClient.setBufferSize(1024 * 1024*10);
ftpClient.connect(ip, port);
//连接
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("FTP server refused connection.");
}
//登录
System.out.println("ftp开始登录:"+username+","+password+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
boolean success = ftpClient.login(username, password);
System.out.println("ftp登录状态:"+success+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
if (!success) {
ftpClient.disconnect();
throw new IOException("Could not login to FTP server.");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
LOCAL_CHARSET = "GBK";
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))){
LOCAL_CHARSET="UTF-8";
}
System.out.println("ftp切换目录"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
boolean changed = ftpClient.changeWorkingDirectory(remoteFile(path));
System.out.println("ftp切换目录结果:"+changed+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
if (!changed) {
ftpClient.disconnect();
throw new IOException("Failed to change to directory: " + path);
}
}
//目录转换
private String remoteFile(String remoteFilePath) throws IOException{
System.out.println("目录转换:"+remoteFilePath+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
return new String(remoteFilePath.getBytes(LOCAL_CHARSET),"iso-8859-1");
}
/**
* 断开与ftp服务器连接
*
* @throws IOException
*/
public void closeServer(){
try{
if (ftpClient != null&&ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
System.out.println("已从服务器断开"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 切换目录
*
* @param path
*/
public void changeDirectory(String path) {
try {
boolean changed = ftpClient.changeWorkingDirectory(remoteFile(path));
if (!changed) {
ftpClient.makeDirectory(remoteFile(path));
ftpClient.changeWorkingDirectory(remoteFile(path));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 切换目录
*
* @param path
*/
public void changeWorkingDirectory(String path) throws IOException {
ftpClient.changeWorkingDirectory(remoteFile(path));
}
/**
* 上传文件
*
* @param data
* @param ftpFile
*/
public Boolean outUploadTxt(String data, String ftpFile) {
System.out.println("outUploadTxt:"+ftpFile);
ByteArrayOutputStream byteArrayOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
boolean done = true;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(data.getBytes());
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
System.out.println("开始请求上传,文件流大小:"+byteArrayOutputStream.size());
//ftpClient.setSoTimeout(60*1000);
//ftpClient.setBufferSize(1024*1024*10);
done = ftpClient.storeFile(remoteFile(ftpFile),byteArrayInputStream);
if (done) {
//传输后发送一个命令,避免传送下1个文件服务器进行拒绝
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))){
LOCAL_CHARSET="UTF-8";
System.out.println("isPositiveCompletion!"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
System.out.println("上传成功!"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
} else {
System.out.println("上传失败!"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (byteArrayOutputStream != null){
byteArrayOutputStream.close();
}
if (byteArrayInputStream != null){
byteArrayInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return done;
}
/**
* 上传文件
*
* @param outputStream
* @param ftpFile
*/
public Boolean outUpload(ByteArrayOutputStream outputStream, String ftpFile) {
ByteArrayInputStream byteArrayInputStream = null;
boolean done = true;
try {
byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
done = ftpClient.storeFile(remoteFile(ftpFile),byteArrayInputStream);
if (done) {
System.out.println("上传成功!"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
} else {
System.out.println("上传失败!"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (byteArrayInputStream != null)
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return done;
}
/**
* 创建本地文件夹
* @param file 路径 + 文件夹名称
*/
public void createFile(String file){
//创建文件夹
Path dirFile = Paths.get(file);
try {
Files.createDirectories(dirFile);
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建目录失败:" + e.getMessage()+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
}
/**
* 写入数据
* @param file 路径 + 文件夹名称 + 文件名
* @param content 数据
*/
public void content(String file,String content){
try{
Path path = Paths.get(file);
Files.write(path, content.getBytes());
} catch (IOException e) {
e.printStackTrace();
System.out.println("写入文件失败:" + e.getMessage()+","+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
}
/**
* 压缩文件
* @param sourceFilePath 源文件路径
* @param zipFilePath 压缩文件路径
* @throws IOException
*/
public void compressFile(String sourceFilePath, String zipFilePath) throws IOException {
FileOutputStream fos = new FileOutputStream(zipFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
addFolderToZip("", sourceFilePath, zos);
zos.close();
fos.close();
}
private void addFileToZip(String path, File file, ZipOutputStream zos) throws IOException {
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(path + file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
private void addFolderToZip(String path, String folderPath, ZipOutputStream zos) throws IOException {
File folder = new File(folderPath);
for (File file : folder.listFiles()) {
if (file.isDirectory()) {
addFolderToZip(path + file.getName() + "/", file.getAbsolutePath(), zos);
} else {
addFileToZip(path, file, zos);
}
}
}
// private void addFileToZip(String filePath, ZipOutputStream zos) throws IOException {
// File file = new File(filePath);
// FileInputStream fis = new FileInputStream(file);
// ZipEntry zipEntry = new ZipEntry(file.getPath());
// zos.putNextEntry(zipEntry);
//
// byte[] bytes = new byte[1024];
// int length;
// while ((length = fis.read(bytes)) >= 0) {
// zos.write(bytes, 0, length);
// }
//
// zos.closeEntry();
// fis.close();
// }
//
// private void addFolderToZip(String folderPath, String srcFolder, ZipOutputStream zos) throws IOException {
// File folder = new File(srcFolder + folderPath);
// for (File file : folder.listFiles()) {
// if (file.isDirectory()) {
// addFolderToZip(folderPath + File.separator + file.getName(), srcFolder, zos);
// } else {
// addFileToZip(srcFolder + File.separator + folderPath + File.separator + file.getName(), zos);
// }
// }
// }
/**
*
* @param localFilePath 本地路径
* @param ftpFilePath ftp路径
* @return
* @throws IOException
*/
public Boolean uploadFileToFtp(String localFilePath, String ftpFilePath) throws IOException {
boolean done = true;
// 上传文件
File file = new File(localFilePath);
InputStream inputStream = new FileInputStream(file);
//FileInputStream inputStream = new FileInputStream(localFilePath);
done = ftpClient.storeFile(file.getName(), inputStream);
inputStream.close();
return done;
}
/**
* 删除文件
* @param filePath 文件路径
*/
public void deleteFile(String filePath){
File directory = new File(filePath);
try {
deleteDirectory(directory);
} catch (Exception e) {
e.printStackTrace();
System.err.println("删除失败: " + e.getMessage());
}
}
private void deleteDirectory(File directory) {
if (directory.exists()) {
File[] files = directory.listFiles();
if (files != null) { // 文件或目录可能为空
for (File file : files) {
if (file.isDirectory()) {
// 递归删除子目录
deleteDirectory(file);
} else {
// 删除文件
file.delete();
}
}
}
// 最后删除目录本身
directory.delete();
}
}
}
sftp上传
package com.xnh.atom.server;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jcraft.jsch.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Vector;
public class SftpChinaFileUtil {
private static final Logger logger = LoggerFactory.getLogger(SftpChinaFileUtil.class);
//session会话
private Session session = null;
//连接通道
private ChannelSftp channel = null;
//超时时间
private int timeout = 60000;
private String LOCAL_CHARSET = "GBK";
/**
* 连接sftp服务器
*/
public boolean connect(String ftpUsername, String ftpAddress, int ftpPort, String ftpPassword) {
boolean isSuccess = false;
if (channel != null) {
System.out.println("通道不为空");
return false;
}
//创建JSch对象
JSch jSch = new JSch();
try {
// 根据用户名,主机ip和端口获取一个Session对象
System.out.println("session创建开始:"+ftpUsername+","+ftpAddress+","+ftpPort);
jSch.getSession(ftpUsername, ftpAddress, ftpPort);
session = jSch.getSession(ftpUsername, ftpAddress, ftpPort);
System.out.println("session创建成功");
//设置密码
session.setPassword(ftpPassword);
System.out.println(ftpPassword);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
//为Session对象设置properties
session.setConfig(config);
//设置超时
session.setTimeout(timeout);
System.out.println("session创建连接");
//通过Session建立连接
session.connect();
System.out.println("session连接成功");
// 打开SFTP通道
channel = (ChannelSftp) session.openChannel("sftp");
// 建立SFTP通道的连接
channel.connect();
isSuccess = true;
} catch (JSchException e) {
logger.error("连接服务器异常", e);
}
return isSuccess;
}
/**
* 关闭连接
*/
public void close() {
//操作完毕后,关闭通道并退出本次会话
if (channel != null && channel.isConnected()) {
channel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
/**
* 文件上传
* @param data 文件数据
* @param dst 上传路径
* @param fileName 上传文件名
* @param document dom对象
* @param preffix 文件后缀
*
* @throws SftpException
* @throws IOException
*/
public boolean upLoadFile(String data, String dst, String fileName,Document document,String prefix) throws SftpException, IOException {
boolean isSuccess = false;
ByteArrayOutputStream byteArrayOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
try {
dst = new String(dst.getBytes(LOCAL_CHARSET),"iso-8859-1");
if(createDir(dst)) {
byteArrayOutputStream = new ByteArrayOutputStream();
if(prefix==null){
logger.info("文件后缀为空:{}",prefix);
return false;
}
//根据文件后缀进行匹配文件 把字符数组转换成输入流进行上传
if(!"xml".equals(prefix)){
byteArrayOutputStream.write(data.getBytes());
}else{
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
byteArrayOutputStream = new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(byteArrayOutputStream, format);
writer.write(document);
writer.close();
}
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
InputStream src = byteArrayInputStream;
channel.put(src, fileName);
isSuccess = true;
}
} catch (SftpException e) {
logger.error(fileName + "文件上传异常", e);
}finally {
try {
if (byteArrayOutputStream != null)
byteArrayOutputStream.close();
if (byteArrayInputStream != null)
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return isSuccess;
}
/**
* 创建一个文件目录
*
* @param createpath 路径
* @return
*/
public boolean createDir(String createpath) {
boolean isSuccess = false;
try {
if (isDirExist(createpath)) {
channel.cd(createpath);
return true;
}
String pathArry[] = createpath.split("/");
StringBuffer filePath = new StringBuffer("/");
for (String path : pathArry) {
if (path.equals("")) {
continue;
}
filePath.append(path +"/");
if (isDirExist(filePath.toString())) {
channel.cd(filePath.toString());
} else {
// 建立目录
channel.mkdir(filePath.toString());
//文件夹授权 读写执行
//channel.chmod(Integer.parseInt("755", 8), filePath.toString());
// 进入并设置为当前目录
channel.cd(filePath.toString());
}
}
channel.cd(createpath);
isSuccess = true;
} catch (SftpException e) {
logger.error("目录创建异常!", e);
}
return isSuccess;
}
/**
* 判断目录是否存在
* @param directory 路径
* @return
*/
public boolean isDirExist(String directory) {
boolean isSuccess = false;
try {
SftpATTRS sftpATTRS = channel.lstat(directory);
isSuccess = true;
return sftpATTRS.isDir();
} catch (Exception e) {
if (e.getMessage().toLowerCase().equals("no such file")) {
isSuccess = false;
}
}
return isSuccess;
}
/**
* 重命名指定文件或目录
*
*/
public boolean rename(String oldPath, String newPath) {
boolean isSuccess = false;
try {
channel.rename(oldPath, newPath);
isSuccess = true;
} catch (SftpException e) {
logger.error("重命名指定文件或目录异常", e);
}
return isSuccess;
}
/**
* 列出指定目录下的所有文件和子目录。
*/
public Vector ls(String path) {
try {
Vector vector = channel.ls(path);
return vector;
} catch (SftpException e) {
logger.error("列出指定目录下的所有文件和子目录。", e);
}
return null;
}
/**
* 删除文件
*
* @param directory linux服务器文件地址
* @param deleteFile 文件名称
*/
public boolean deleteFile(String directory, String deleteFile) {
boolean isSuccess = false;
try {
channel.cd(directory);
channel.rm(deleteFile);
isSuccess = true;
} catch (SftpException e) {
logger.error("删除文件失败", e);
}
return isSuccess;
}
/**
* 下载文件
*
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 下载到本地路径
*/
public boolean download(String directory, String downloadFile, String saveFile) {
boolean isSuccess = false;
try {
channel.cd(directory);
File file = new File(saveFile);
channel.get(downloadFile, new FileOutputStream(file));
isSuccess = true;
} catch (SftpException e) {
logger.error("下载文件失败", e);
} catch (FileNotFoundException e) {
logger.error("下载文件失败", e);
}
return isSuccess;
}
/**
* 上传压缩包
* @param localFile 本地路径
* @param sftpFile sftp路径
* @return
* @throws SftpException
* @throws IOException
*/
public void upLoadFile(String localFile,String sftpFile){
try {
sftpFile = new String(sftpFile.getBytes(LOCAL_CHARSET),"iso-8859-1");
if(createDir(sftpFile)) {
File localZipFile = new File(localFile);
InputStream inputStream = new FileInputStream(localZipFile);
channel.put(inputStream, sftpFile + "/" + localZipFile.getName());
inputStream.close();
}
} catch (IOException e) {
logger.error("上传压缩包失败", e);
} catch (SftpException e) {
// TODO Auto-generated catch block
logger.error("上传压缩包失败", e);
}
}
}
获取本地 temp 目录 String tempDir = System.getProperty(“java.io.tmpdir”);
调用上传
if ("0".equals(fileType)){
System.out.println("-----上传----"+"/"+dateString+"/"+fileName+".txt"+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
flag = ftpUtil.outUploadTxt(TempStr, "/"+dateString+"/"+fileName+".txt");
//ftpUtil.closeServer();
ftpUtil.changeWorkingDirectory(ftpUrl);
}else{
OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
// 5、生成xml文件
ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
writer.close();
flag = ftpUtil.outUpload(out,"/"+dateString+"/"+fileName+".xml");
//ftpUtil.closeServer();
ftpUtil.changeWorkingDirectory(ftpUrl);
}
以及document转string
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8"); // 设置编码格式
// 创建一个StringWriter,它将用于收集XML内容
StringWriter writer = new StringWriter();
// 创建一个XMLWriter,用于将Document对象写入StringWriter
XMLWriter xmlWriter = new XMLWriter(writer, format);
// 将Document对象写入StringWriter
try {
xmlWriter.write(document);
// 关闭XMLWriter,释放资源
xmlWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return writer.toString();