目的:实现FTP文件(.txt)不下载,并且压缩成ZIP文件包输入流作为附件,去发送邮件给用户
FTP操作类:
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class FtpUtil {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
/**
* 获取FTPClient对象
*
* @param ftpHost
* FTP主机服务器
* @param ftpPassword
* FTP 登录密码
* @param ftpUserName
* FTP登录用户名
* @param ftpPort
* FTP端口 默认为21
* @return
*/
public static FTPClient getFTPClient(String ftpHost, int ftpPort, String ftpUserName,
String ftpPassword) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("FTP connect failed ,user or password is error");
ftpClient.disconnect();
} else {
logger.info("FTP Connect Success");
}
} catch (Exception ex) {
logger.error("getFTPClient :"+ex.getMessage(),ex);
}
return ftpClient;
}
/**
* 下载文件
*
* @param ftpHost ftp服务器地址
* @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录
* @param ftpPassword 指定用户密码
* @param ftpPort ftp服务员器端口号
* @param ftpPath ftp文件存放物理路径
* @param fileName 文件路径
* @param input 文件输入流,即从本地服务器读取文件的IO输入流
*/
public static void downloadFile(String ftpHost, int ftpPort, String ftpUserName,
String ftpPassword, String ftpPath, String localPath,
String fileName) {
FTPClient ftpClient = null;
try {
ftpClient = getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);//目录最前面不能以'/'开头,否则会读不到内容
File localFile = new File(localPath + File.separatorChar + fileName);
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(fileName, os);
os.close();
ftpClient.logout();
} catch (Exception ex) {
logger.error("downloadFile :"+ex.getMessage(),ex);
}
}
/**
* 上传文件
*
* @param ftpHost ftp服务器地址
* @param ftpUserName anonymous匿名用户登录,不需要密码。administrator指定用户登录
* @param ftpPassword 指定用户密码
* @param ftpPort ftp服务员器端口号
* @param ftpPath ftp文件存放物理路径
* @param fileName 文件路径
* @param input 文件输入流,即从本地服务器读取文件的IO输入流
*/
public static void uploadFile(String ftpHost, int ftpPort, String ftpUserName,
String ftpPassword, String ftpPath,
String fileName,InputStream input){
FTPClient ftp=null;
try {
ftp=getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
ftp.changeWorkingDirectory(ftpPath);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
fileName=new String(fileName.getBytes("GBK"),"iso-8859-1");
ftp.storeFile(fileName, input);
input.close();
ftp.logout();
System.out.println("Upload Success!");
} catch (Exception ex) {
logger.error("UploadFile :"+ex.getMessage(),ex);
}
}
}
File操作类:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
private FileUtils() {
throw new IllegalStateException("Utility class");
}
public static boolean existsFile(String fpath) {
boolean ret = false;
File file = null;
try {
file = new File(fpath);
ret = file.isFile() && file.exists();
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
public static boolean existsDirectory(String fpath) {
boolean ret = false;
File file = null;
try {
file = new File(fpath);
ret = file.isDirectory() && file.exists();
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
/**
* @Description 获取文件名,结尾带上.后缀名
* @param fpath
* @return
*/
public static String getName(String fpath) {
String ret = null;
// tmp vars
File file = null;
if (StringUtils.isEmpty(fpath)) {
return null;
}
try {
if (!fpath.contains("/")) {
return null;
}
if ("/".equals(fpath.substring(fpath.length() - 2,
fpath.length() - 1))) {
return null;
} else {
file = new File(fpath);
if (!file.isDirectory()) {
ret = fpath.substring(fpath.lastIndexOf('/') + 1,
fpath.length());
}
}
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
/**
* @Description 获取文件名称,且结尾不带。后缀名
* @param fpath
* @return
*/
public static String getNameWithoutExtension(String fpath) {
String ret = null;
// tmp vars
File file = null;
String fname = null;
if (StringUtils.isEmpty(fpath)) {
return null;
}
try {
if (!fpath.contains("/")) {
return null;
}
if ("/".equals(fpath.substring(fpath.length() - 2,
fpath.length() - 1))) {
return null;
} else {
file = new File(fpath);
if (file.isDirectory()) {
return null;
} else {
fname = fpath.substring(fpath.lastIndexOf('/') + 1,
fpath.length());
if (!fname.contains(".")) {
ret = fname;
} else {
ret = fname.substring(0, fname.lastIndexOf('.'));
}
}
}
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
/**
* @Description 获取文件的扩展名,中间不带.
* @param fpath
* @return
*/
public static String getExtension(String fpath) {
String ret = null;
// tmp vars
File file = null;
String fname = null;
if (StringUtils.isEmpty(fpath)) {
return null;
}
try {
if (!fpath.contains("/")) {
return null;
}
if ("/".equals(fpath.substring(fpath.length() - 2,
fpath.length() - 1))) {
return null;
} else {
file = new File(fpath);
if (file.isDirectory()) {
return null;
} else {
fname = fpath.substring(fpath.lastIndexOf('/') + 1,
fpath.length());
if (!fname.contains(".")) {
return null;
}
ret = fpath.substring(fpath.lastIndexOf('.') + 1,
fpath.length());
}
}
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
/**
* @Description 返回文件目录,结尾不带/
* @param fpath
* @return
*/
public static String getPath(String fpath) {
String ret = null;
// tmp vars
File file = null;
String fname = null;
if (StringUtils.isEmpty(fpath)) {
return null;
}
try {
if (!fpath.contains("/")) {
return null;
}
if ("/".equals(fpath.substring(fpath.length() - 2,
fpath.length() - 1))) {
ret = fpath;
} else {
file = new File(fpath);
if (file.isFile()) {
ret = file.getParent();
} else {
fname = fpath.substring(fpath.lastIndexOf('/') + 1,
fpath.length());
if (!fname.contains(".")) {
ret = fpath;
} else {
ret = fpath.substring(0, fpath.lastIndexOf('/'));
}
}
}
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
public static boolean createDirectory(String dir) {
// return
boolean ret = false;
File file = null;
try {
file = new File(dir);
if (!file.exists()) {
file.mkdirs();
ret = true;
} else {
ret = true;
}
} catch (Exception e) {
// nothing
} finally {
if(file != null)
file = null;
}
return ret;
}
public static boolean writeFile(String fpath, List<String> textList,
String lineSplit) {
// return
boolean ret = false;
// tmp vars
boolean flagSplitLine = lineSplit != null && lineSplit.length() > 0;
boolean flagWriteText = textList != null && !textList.isEmpty();
if(StringUtils.isEmpty(fpath)) {
return false;
}
createDirectory(getPath(fpath));
try(FileWriter fw = new FileWriter(fpath)) {
if (flagWriteText) {
if (flagSplitLine) {
for (String text : textList) {
fw.append(text);
fw.append(lineSplit);
}
} else {
for (String text : textList) {
fw.append(text);
}
}
}
} catch (Exception e) {
// nothing
}
return ret;
}
public static List<String> readFile(String fpath) {
List<String> textList = null;
textList = new ArrayList<>();
Path path = Paths.get(fpath);
try (BufferedReader in = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
while (in.ready()) {
textList.add(in.readLine());
}
} catch (Exception e) {
// nothing
}
return textList;
}
}
String操作类:
public class StringUtils {
private StringUtils() {
throw new IllegalStateException("Utility class");
}
/*
* 补齐字符串:右边补齐
*/
public static final String rightPad(String str, int size, char padchar) {
int i = 0;
StringBuilder sbBuilder = null;
String ret = null;
if (str == null) {
return null;
}
if ((size - str.length()) <= 0) {
return str;
}
size = size - str.length();
sbBuilder = new StringBuilder();
while (++i <= size) {
sbBuilder.append(padchar);
}
sbBuilder.insert(0, str);
ret = sbBuilder.toString();
return ret;
}
/*
* 补齐字符串:左边补齐
*/
public static final String leftPad(String str, int size, char padchar) {
int i = 0;
StringBuilder sbBuilder = null;
String ret = null;
if (str == null) {
return null;
}
if ((size - str.length()) <= 0) {
return str;
}
size = size - str.length();
sbBuilder = new StringBuilder();
while (++i <= size) {
sbBuilder.append(padchar);
}
sbBuilder.append(str);
ret = sbBuilder.toString();
return ret;
}
/**
* 检测某个字符变量是否为空;<br>
* 为空的情况,包括:null,空串或只包含可以被 trim() 的字符;
*/
public static final boolean isEmpty(String value) {
return (value == null || value.trim().length() == 0);
}
}
邮件操作类:
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import bill.common.utils.FileUtils;
import bill.common.utils.StringUtils;
import javax.mail.internet.MimeMessage;
public class MailHelper {
private static Logger logger = LoggerFactory.getLogger(MailHelper.class);
private static Object lockMail = 1;
private static JavaMailSenderImpl mailSender = null;
private static String mailFrom = null;
public MailHelper(String host, Integer port, String strMailFrom) {
synchronized (lockMail) {
if (mailSender == null) {
mailSender = new JavaMailSenderImpl();
mailSender.setHost(host);
mailSender.setPort(port);
mailFrom = strMailFrom;
}
}
}
public boolean sendMail(String encodingName, String subject, String body, String[] to, String[] cc) {
try {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper mail = new MimeMessageHelper(msg, true, encodingName); // "UTF-8"
mail.setFrom(mailFrom);
if (to != null && to.length > 0) {
for (String item : to) {
if (!StringUtils.isEmpty(item)) {
mail.addTo(item);
}
}
}
if (cc != null && cc.length > 0) {
for (String item : cc) {
if (!StringUtils.isEmpty(item)) {
mail.addCc(item);
}
}
}
mail.setSubject(subject);
mail.setText(body, true);
mailSender.send(msg);
return true;
} catch (Exception e) {
logger.error("sendMail(), ex = {}", e.getMessage());
return false;
}
}
public boolean sendMail(String encodingName, String subject, String body, String[] to, String[] cc,
List<String> attachments) {
try {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper mail = new MimeMessageHelper(msg, true, encodingName);
mail.setFrom(mailFrom);
if (to != null && to.length > 0) {
for (String item : to) {
if (!StringUtils.isEmpty(item)) {
mail.addTo(item);
}
}
}
if (cc != null && cc.length > 0) {
for (String item : cc) {
if (!StringUtils.isEmpty(item)) {
mail.addCc(item);
}
}
}
mail.setSubject(subject);
mail.setText(body, true);
for (String attachments_i : attachments) {
FileSystemResource file = new FileSystemResource(attachments_i);
mail.addAttachment(FileUtils.getName(attachments_i), file);
}
mailSender.send(msg);
return true;
} catch (Exception e) {
logger.error("sendMailWithAttachment(), ex = {}", e.getMessage());
return false;
}
}
public boolean sendMail(String encodingName, String subject, String body, String[] to, String[] cc,
String attachname,InputStreamSource inputstream) {
try {
MimeMessage msg = mailSender.createMimeMessage();
MimeMessageHelper mail = new MimeMessageHelper(msg, true, encodingName);
mail.setFrom(mailFrom);
if (to != null && to.length > 0) {
for (String item : to) {
if (!StringUtils.isEmpty(item)) {
mail.addTo(item);
}
}
}
if (cc != null && cc.length > 0) {
for (String item : cc) {
if (!StringUtils.isEmpty(item)) {
mail.addCc(item);
}
}
}
mail.setSubject(subject);
mail.setText(body, true);
mail.addAttachment(attachname, inputstream);
mailSender.send(msg);
return true;
} catch (Exception e) {
logger.error("sendMailWithAttachmentStream(), ex = {}", e.getMessage());
return false;
}
}
}
Date操作类:
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateUtils {
/*
* 计算两个时间的时间差, 返回格式为:dd hh:mm:ss:fff
*/
public static final String getTimeSpan(Date dateEnd, Date dateStart) {
String ret = "";
try {
long dateDiff = dateEnd.getTime() - dateStart.getTime();
long day = dateDiff / (1000 * 60 * 60 * 24);
long hour = dateDiff % (1000 * 60 * 60 * 24) / (1000 * 60 * 60);
long min = dateDiff % (1000 * 60 * 60) / (1000 * 60);
long sec = dateDiff % (1000 * 60) / (1000);
long msec = dateDiff % 1000;
ret = MessageFormat.format("{0} {1}:{2}:{3}:{4}",
StringUtils.leftPad(String.valueOf(day), 2, '0'),
StringUtils.leftPad(String.valueOf(hour), 2, '0'),
StringUtils.leftPad(String.valueOf(min), 2, '0'),
StringUtils.leftPad(String.valueOf(sec), 2, '0'),
StringUtils.leftPad(String.valueOf(msec), 3, '0'));
} catch (Exception e) {
// nothing
}
return ret;
}
public enum TimeTypeEnum {
/**
* @Field @YEAR : YEAR
*/
YEAR("YEAR", 1),
/**
* @Field @MONTH : MONTH
*/
MONTH("MONTH", 2),
/**
* @Field @WEEK_OF_YEAR : WEEK_OF_YEAR
*/
WEEK_OF_YEAR("WEEK_OF_YEAR", 3),
/**
* @Field @WEEK_OF_MONTH : WEEK_OF_MONTH
*/
WEEK_OF_MONTH("WEEK_OF_MONTH", 4),
/**
* @Field @DAY_OF_MONTH : DAY_OF_MONTH
*/
DATE("DATE", 5),
/**
* @Field @DAY_OF_MONTH : DAY_OF_MONTH
*/
DAY_OF_MONTH("DAY_OF_MONTH", 5),
/**
* @Field @DAY_OF_YEAR : DAY_OF_YEAR
*/
DAY_OF_YEAR("DAY_OF_YEAR", 6),
/**
* @Field @DAY_OF_WEEK : DAY_OF_WEEK
*/
DAY_OF_WEEK("DAY_OF_WEEK", 7),
/**
* @Field @DAY_OF_WEEK_IN_MONTH : DAY_OF_WEEK_IN_MONTH
*/
DAY_OF_WEEK_IN_MONTH("DAY_OF_WEEK_IN_MONTH", 8);
private String name;
private int value;
private TimeTypeEnum(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
}
public static final Date addTime(Date date, TimeTypeEnum timeType,
int timeDiff) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
/*
* calendar.add(calendar.YEAR, 1);//把日期往后增加一年.整数往后推,负数往前移动
* calendar.add(calendar.DAY_OF_MONTH, 1);//把日期往后增加一个月.整数往后推,负数往前移动
* calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
* calendar.add(calendar.WEEK_OF_MONTH, 1);//把日期往后增加一个月.整数往后推,负数往前移动
*/
calendar.add(timeType.getValue(), timeDiff);
date = calendar.getTime(); // 这个时间就是日期往后推一天的结果
return date;
}
public static String parseDateToString(Date date, String format) {
SimpleDateFormat sf = null;
String retString = null;
sf = new SimpleDateFormat(format);
retString = sf.format(date);
return retString;
}
}
配置加载类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PsbcModel{
public static String MAILSMTPSERVER;
public static int MAILSMTPPORT;
public static String MAILSMTPFROM;
public static String MAILTO;
public static String MAILCC;
public static String MAILSUBJECT;
public static String MAILBODY;
public static String MAILSMTPCODE;
public static String FTPSERVERHOST;
public static Integer FTPSERVERPORT;
public static String FTPSERVERROOTPATH;
public static String FTPSERVERUSER;
public static String FTPSERVERPASSWORD;
public static Integer FTPSERVERTIMEOUT;
public static String FTPDIR;
@Value("${notify_smtp_server}")
public void setMailSmtpServer(String mailSmtpServer) {
MAILSMTPSERVER = mailSmtpServer;
}
@Value("${notify_smtp_port}")
public void setMailSmtpPort(Integer mailSmtpPort) {
MAILSMTPPORT = mailSmtpPort;
}
@Value("${notify_smtp_from}")
public void setFrom(String from) {
MAILSMTPFROM = from;
}
@Value("${notify_succ_to}")
public void setTo(String to) {
MAILTO = to;
}
@Value("${notify_succ_cc}")
public void setCc(String cc) {
MAILCC = cc;
}
@Value("${notify_succ_subject}")
public void setSubject(String subject) {
MAILSUBJECT = subject;
}
@Value("${notify_succ_body}")
public void setBody(String body) {
MAILBODY = body;
}
@Value("${notify_smtp_code}")
public void setCode(String code) {
MAILSMTPCODE = code;
}
@Value("${ftp_server_host}")
public void setHostname(String hostname) {
FTPSERVERHOST = hostname;
}
@Value("${ftp_server_port}")
public void setPort(int port) {
FTPSERVERPORT = port;
}
@Value("${ftp_server_root_path}")
public void setRootPath(String rootPath) {
FTPSERVERROOTPATH = rootPath;
}
@Value("${ftp_server_user}")
public void setUser(String user) {
FTPSERVERUSER = user;
}
@Value("${ftp_server_password}")
public void setPassword(String password) {
FTPSERVERPASSWORD = password;
}
@Value("${ftp_server_timeout}")
public void setFtpTimeOut(Integer timeout) {
FTPSERVERTIMEOUT = timeout;
}
@Value("${ftp_server_dir}")
public void setFtpDir(String ftpdir) {
FTPDIR = ftpdir;
}
}
实现类:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import bill.common.ftp.FtpUtil;
import bill.common.mail.MailHelper;
import bill.common.utils.DateUtils;
import bill.service.PsbcBillService;
import bill.service.model.PsbcModel;
@Service
public class PsbcBillServiceImpl implements PsbcBillService {
@Autowired
private MailWorkServiceImpl mailServerImp;
private static Logger logger = LoggerFactory.getLogger(PsbcBillServiceImpl.class);
@Override
public void executeTask() {
try{
Date dNow = new Date();
Calendar calendar = Calendar.getInstance(); //得到日历
calendar.setTime(dNow);//把当前时间赋给日历
calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
Date dBefore = calendar.getTime(); //得到前一天的时间
String fileName="PSBC"+DateUtils.parseDateToString(dBefore, "yyyyMMdd")+".txt";
String ftpHost = PsbcModel.FTPSERVERHOST;
int ftpPort = PsbcModel.FTPSERVERPORT;
String ftpUserName = PsbcModel.FTPSERVERUSER;
String ftpPassword = PsbcModel.FTPSERVERPASSWORD;
String ftpPath=PsbcModel.FTPDIR;
FTPClient ftpClient = FtpUtil.getFTPClient(ftpHost, ftpPort, ftpUserName, ftpPassword);
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setConnectTimeout(60000);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);//目录最前面不能以'/'开头,否则会读不到内容
InputStream inputStream=ftpClient.retrieveFileStream(fileName);
if(inputStream == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE){
logger.info("FTP file not exist");
SendMailNoAttachment("清算文件:【"+fileName+"】不存在,请联系供应商!");
}else{
String zipName="PSBC"+DateUtils.parseDateToString(dBefore, "yyyyMMdd")+".zip";
SendEmail(getCompressed(inputStream,fileName),zipName);
inputStream.close();
}
ftpClient.disconnect();
logger.info("FTP Disconnect");
}catch(Exception ex){
logger.error("PsbcBillServiceImpl executeTask ==> happen exception = ",ex.getMessage(),ex);
}
}
//将FTP文件输入流转换成ZIP的文件的输入流
public InputStream getCompressed(InputStream is,String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
ZipOutputStream zos = new ZipOutputStream(bos);
zos.putNextEntry(new ZipEntry(fileName));
int count;
byte data[] = new byte[2048];
BufferedInputStream entryStream = new BufferedInputStream(is, 2048);
while ((count = entryStream.read(data, 0, 2048)) != -1) {
zos.write( data, 0, count );
}
logger.info("压缩成功");
entryStream.close();
zos.closeEntry();
zos.close();
}catch(Exception ex){
logger.error("getCompressed executeTask ==> happen exception = ",ex.getMessage(),ex);
}
return new ByteArrayInputStream(bos.toByteArray());
}
//将FTP文件输入流压缩成ZIP文件
public void zipUtil(InputStream ins,String zipNamePath,String fileName){
//输入
BufferedInputStream bin = null;
DataInputStream dis = null;
//输出
File outfile = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
ZipEntry ze = null;
try {
//输入-获取数据
bin = new BufferedInputStream(ins);
dis = new DataInputStream(bin); //增强
//输出-写出数据
outfile = new File(zipNamePath);
fos = new FileOutputStream(outfile);
bos = new BufferedOutputStream(fos, 1024); //the buffer size
zos = new ZipOutputStream(bos); //压缩输出流
ze = new ZipEntry(fileName); //实体ZipEntry保存
zos.putNextEntry(ze);
int len = 0;//临时文件
byte[] bts = new byte[1024]; //读取缓冲
while((len=dis.read(bts)) != -1){ //每次读取1024个字节
System.out.println(len);
zos.write(bts, 0, len); //每次写len长度数据,最后前一次都是1024,最后一次len长度
}
logger.info("压缩成功");
} catch (Exception ex) {
logger.error("zipUtil ==> happen exception = ",ex.getMessage(),ex);
ex.printStackTrace();
} finally{
try { //先实例化后关闭
zos.closeEntry();
zos.close();
bos.close();
fos.close();
dis.close();
bin.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//通过文件输入流发送邮件
private void SendEmail(InputStream is,String fileName){
Properties props = new Properties();
//props.put("mail.smtp.starttls.enable", true);
//设置邮件服务域名
props.put("mail.smtp.host", PsbcModel.MAILSMTPSERVER);
//设置邮件服务端口
props.put("mail.smtp.port", PsbcModel.MAILSMTPPORT);
Session session = Session.getInstance(props);
try {
//邮件
Message message = new MimeMessage(session);
//设置邮件发送人
message.setFrom(new InternetAddress(PsbcModel.MAILSMTPFROM));
//设置邮件收件人
Address[] toReceives = null;
String[] receivers = PsbcModel.MAILTO.split(",");
if (receivers != null&&receivers.length>0){
// 为每个邮件接收者创建一个地址
toReceives = new InternetAddress[receivers.length];
for (int i=0; i<receivers.length; i++){
toReceives[i] = new InternetAddress(receivers[i]);
}
// 将所有接收者地址都添加到邮件接收者属性中
message.setRecipients(Message.RecipientType.TO, toReceives);
}
//设置邮件主题
message.setSubject(PsbcModel.MAILSUBJECT);
//整封邮件的MINE消息体
MimeMultipart msgMultipart = new MimeMultipart ("mixed");
//设置邮件的MINE消息体
message.setContent(msgMultipart);
//附件
MimeBodyPart attchPart = new MimeBodyPart();
//正文内容
MimeBodyPart htmlPart = new MimeBodyPart();
//把内容,附件加入到 MINE消息体中
msgMultipart.addBodyPart(attchPart);
msgMultipart.addBodyPart(htmlPart);
//添加正文内容
htmlPart.setContent(PsbcModel.MAILBODY,"text/html;charset=utf-8");
//添加附件
DataSource dataSource=new ByteArrayDataSource(is, "application/zip");
DataHandler dataHandler=new DataHandler(dataSource);
attchPart.setDataHandler(dataHandler);
attchPart.setFileName(MimeUtility.encodeText(fileName));
logger.info("Start Send");
Transport.send(message);
logger.info("End Send");
} catch (Exception e) {
logger.info("SendEmail:"+e.getMessage(),e);
e.printStackTrace();
}
}
private void SendMailNoAttachment(String body){
try {
String[] to=PsbcModel.MAILTO.split(",");
String[] cc=PsbcModel.MAILCC.split(",");
MailHelper mail=new MailHelper(PsbcModel.MAILSMTPSERVER,PsbcModel.MAILSMTPPORT,PsbcModel.MAILSMTPFROM);
mail.sendMail(PsbcModel.MAILSMTPCODE, PsbcModel.MAILSUBJECT, body, to, cc);
} catch (Exception e) {
logger.info("SendMailNoAttachment:"+e.getMessage(),e);
e.printStackTrace();
}
}
}
上面的代码删减了一些内容,可能会报错,所以需要自己去整理。