ElasticSearch工具类
/**
* es factory
*/
public class ESClientFactory {
private static final Logger logger = LoggerFactory.getLogger(ESClientFactory.class);
public static TransportClient getClient(String clusterName, String hostName, Integer port) {
logger.info("clusterName:{}, hostName:{}, port:{}", clusterName, hostName, port);
System.setProperty("es.set.netty.runtime.available.processors", "false");
TransportClient client = null;
try {
Settings settings = Settings.builder().put("cluster.name", clusterName)
//.put("node.name", "node-1")
//.put("client.transport.sniff", true) // true 把集群中其它机器的ip地址加到客户端中
.build();
client = new PreBuiltTransportClient(settings)
.addTransportAddresses(new TransportAddress(InetAddress.getByName(hostName), port));
if (null == client){
logger.error("TransportClient is null, by clusterName:{}, hostName:{}, port:{}", clusterName, hostName, port);
throw new Exception("TransportClient is null");
}
} catch (UnknownHostException e) {
logger.error("unkown host: {}", e);
} catch (Exception e) {
logger.error("GetClient has error: {}", e);
throw new Exception("GetClient has error: {}",e);
} finally {
return client;
}
}
public static void close(TransportClient client) {
if (null != client) {
client.close();
}
}
}
HBase工具类
/**
* @author feng.wei
* @date 2018/7/16
*/
public class HConnectionFactory {
private static Logger logger = LoggerFactory.getLogger(HConnectionFactory.class);
public static Configuration getConfiguration(String quorum, String zNode, String port){
Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", quorum);
configuration.set("hbase.zookeeper.property.clientPort", port);
configuration.set("zookeeper.znode.parent", zNode);
return configuration;
}
public static org.apache.hadoop.hbase.client.Connection getHConnection(Configuration configuration) {
org.apache.hadoop.hbase.client.Connection connection = null;
try {
connection = ConnectionFactory.createConnection(configuration);
} catch (IOException e) {
logger.error("获取HBase connection出错:{}", e);
}
return connection;
}
public static org.apache.hadoop.hbase.client.Connection getHConnection(String zkAddress, String zNode, String port) {
org.apache.hadoop.hbase.client.Connection connection = null;
try {
connection = ConnectionFactory.createConnection(getConfiguration(zkAddress, zNode, port));
} catch (IOException e) {
logger.error("获取HBase connection出错:{}", e);
}
return connection;
}
}
日期处理
/**
* 日期常用格式转换
*/
public class DateTimeUtil {
static {
ymdhmsFormat = new SimpleDateFormat("yyyyMMddHHmmss");
ymdhmsFormat2 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
ymdFormat = new SimpleDateFormat("yyyyMMdd");
ymdFormat2 = new SimpleDateFormat("yyyy-MM-dd");
hmsFormat = new SimpleDateFormat("HHmmss");
ymFormat = new SimpleDateFormat("yyyyMM");
c = Calendar.getInstance();
}
private static SimpleDateFormat ymdhmsFormat;
private static SimpleDateFormat ymdhmsFormat2;
private static SimpleDateFormat ymdFormat;
private static SimpleDateFormat ymdFormat2;
private static SimpleDateFormat hmsFormat;
private static SimpleDateFormat ymFormat;//年月
private static Calendar c;
public static Date dateOnly(Date date) {
return yyyyMMddToDate(parseToyyyyMMdd(date));
}
/**
* 转换为 yyyyMMddHHmmss格式
*/
public static String parseToyyyyMMddHHmmss(Date date) {
if (date == null) {
return null;
}
return ymdhmsFormat.format(date);
}
/**
* 转换为 yyyyMMdd HH:mm:ss格式
*/
public static String parseToyyyyMMddHHmmss2(Date date) {
if (date == null) {
return null;
}
return ymdhmsFormat2.format(date);
}
/**
* 转换为HHmmss格式
*/
public static String parseToHHmmss(Date date) {
if (date == null) {
return null;
}
return hmsFormat.format(date);
}
/**
* 转换为yyyyMMdd格式
*/
public static String parseToyyyyMMdd(Date date) {
if (date == null) {
return null;
}
return ymdFormat.format(date);
}
/**
* 转换为yyyyMM格式
*/
public static int parseToyyyyMM(Date date) {
if (date == null) {
return 0;
}
return Integer.valueOf(ymFormat.format(date));
}
public static Date yyyyMMddHHmmssToDate(String yyyyMMddHHmmss) {
try {
return ymdhmsFormat.parse(yyyyMMddHHmmss);
} catch (Exception e) {
return null;
}
}
public static Date yyyyMMddToDate(String yyyyMMdd) {
try {
return ymdFormat.parse(yyyyMMdd);
} catch (Exception e) {
return null;
}
}
public static Date yyyyMMToDate(String yyyyMM) {
try {
return ymFormat.parse(yyyyMM);
} catch (Exception e) {
return null;
}
}
/**
* yyyy-MM-dd转换成date
*
* @param yyyyMMdd2
* @return
* @author linbingwen
* @since 2016年4月14日
*/
public static Date yyyyMMddToDate2(String yyyyMMdd2) {
try {
return ymdFormat2.parse(yyyyMMdd2);
} catch (Exception e) {
return null;
}
}
public static Date HHmmssToDate(String HHmmss) {
try {
return hmsFormat.parse(HHmmss);
} catch (Exception e) {
return null;
}
}
public static Date getDate(Date srcDate, Integer daysToAdd) {
c.setTime(srcDate);
c.add(Calendar.DATE, daysToAdd); // number of days to add
return c.getTime();
}
public static Date yyyyMMddHHmmssToDate2(String yyyyMMddHHmmss) {
try {
return ymdhmsFormat2.parse(yyyyMMddHHmmss);
} catch (Exception e) {
return null;
}
}
public static final int daysBetween(Date early, Date late) {
java.util.Calendar calst = java.util.Calendar.getInstance();
java.util.Calendar caled = java.util.Calendar.getInstance();
calst.setTime(early);
caled.setTime(late);
// 设置时间为0时
calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
calst.set(java.util.Calendar.MINUTE, 0);
calst.set(java.util.Calendar.SECOND, 0);
caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
caled.set(java.util.Calendar.MINUTE, 0);
caled.set(java.util.Calendar.SECOND, 0);
// 得到两个日期相差的天数
int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;
return days;
}
public static Date getNextDayOfWeek(Date date, int dayOfWeek) {
if (dayOfWeek == 0) {
dayOfWeek = 7;
}
if (dayOfWeek > 7 || dayOfWeek < 1) {
throw new RuntimeException("星期:" + dayOfWeek + "不存在");
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
while (true) {
int day = cal.get(Calendar.DAY_OF_WEEK);
if (preWeekDay(day) == dayOfWeek) {
return cal.getTime();
}
cal.add(Calendar.DATE, 1);
}
}
public static Date getNextMonthDate(Date date, int nextMonthDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int day = cal.get(Calendar.DATE);
if (day <= nextMonthDate) {
cal.set(Calendar.DATE, nextMonthDate);
} else {
cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DATE, nextMonthDate);
}
return cal.getTime();
}
public static int nextWeekDay(int day) {
if (day == 7) {
return 1;
} else {
return day++;
}
}
public static int preWeekDay(int day) {
if (day == 1) {
return 7;
} else {
return day - 1;
}
}
/**
* 计算两个日期相差的天数
*
* @param beginDate 【YYYYMMDD】
* @param endDate 【YYYYMMDD】
* @return Integer
* @author linbingwen
* @since 2015年7月21日
*/
public static long diffDate(Date beginDate, Date endDate) {
Calendar theCa1 = Calendar.getInstance();
Calendar theCa2 = Calendar.getInstance();
theCa1.setTime(beginDate);
theCa2.setTime(endDate);
long between_days = (theCa2.getTimeInMillis() - theCa1.getTimeInMillis()) / (1000 * 3600 * 24);
return between_days;
}
/**
* 分钟差
*
* @param @param beginDate
* @param @param endDate
* @param @return 设定文件
* @return long 返回类型
* @Title: diffMinute
* @Description: TODO
* @author : liuqiuyun
* @throws
*/
public static long diffMinute(Date beginDate, Date endDate) {
Calendar theCa1 = Calendar.getInstance();
Calendar theCa2 = Calendar.getInstance();
theCa1.setTime(beginDate);
theCa2.setTime(endDate);
long between_minutes = (theCa2.getTimeInMillis() - theCa1.getTimeInMillis()) / (1000 * 60);
return between_minutes;
}
/**
* 获取月份差第一天
*
* @param @param date
* @param @param monthToAdd
* @param @param minOrMax 月初还是月末
* @param @return 设定文件
* @return Date 返回类型
* @Title: getMonthFirstDate
* @Description: TODO
* @author : liuqiuyun
* @throws
*/
public static Date getMonthFirstDate(Date date, int monthToAdd, String minOrMax) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, monthToAdd);
if (minOrMax.equals("min")) {
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
} else if (minOrMax.equals("max")) {
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}
return calendar.getTime();
}
public static long getLastMonth(Date date) {
Date lastDate = getMonthFirstDate(date, -1, "min");
long lastMonth = parseToyyyyMM(lastDate);
return lastMonth;
}
public static void main(String[] args) throws InterruptedException {
// Calendar cal = Calendar.getInstance();
// System.out.println(" cal.get(Calendar.DAY_OF_WEEK);:" + cal.get(Calendar.DAY_OF_WEEK));
// System.out.println(" cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);:" + cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
//
// System.out.println(getNextDayOfWeek(cal.getTime(), 0));
// System.out.println(getNextDayOfWeek(cal.getTime(), 7));
// System.out.println(getNextDayOfWeek(cal.getTime(), 1));
// System.out.println(getNextDayOfWeek(cal.getTime(), 2));
//
// System.out.println(getNextMonthDate(cal.getTime(), 0));
// System.out.println(parseToyyyyMMdd(getNextMonthDate(cal.getTime(), 15)));
System.out.println(parseToyyyyMMdd(getMonthFirstDate(yyyyMMddToDate("20160618"), -1, "max")));
// System.out.println(yyyyMMddToDate2("2012-09-01"));
//
// Date start = new Date();
// System.out.println(start);
// Thread.sleep(60*1000*5+1000);
// Date end = new Date();
// System.out.println(end);
// System.out.println(diffMinute(start,end));
}
}
字符串处理
字符串处理的常用工具包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
分页工具类
/**
* 分页工具类
*/
public class SharePager {
private int totalRows; //总行数
private int pageSize = 20; //每页显示的行数
private int currentPage; //当前页号
private int totalPages; //总页数
private int startRow; //当前页在数据库中的起始行
/**
* 默认构造函数
*/
public SharePager() {
}
/**
* 默认每页10行
*
* @param totalRows
*/
public SharePager(int totalRows) {
this.totalRows = totalRows;
totalPages = (int) Math.ceil((double) totalRows / (double) pageSize);
startRow = 0;
}
/**
* 可自定义每页显示多少页
*
* @param totalRows
* @param pageSize
*/
public SharePager(int totalRows, int pageSize) {
this.totalRows = totalRows;
this.pageSize = pageSize;
if (this.pageSize < 1) {
this.pageSize = 1;
} else if (pageSize > 20) {
this.pageSize = 20;
}
// if(this.pageSize>totalRows){
// this.pageSize=(int)totalRows;
// }
totalPages = (int) Math.ceil((double) totalRows / (double) this.pageSize);
currentPage = 1;
startRow = 0;
}
/**
* 跳转到首页
*/
public void first() {
this.currentPage = 1;
this.startRow = 0;
}
/**
* 跳转到上一页
*/
public void previous() {
if (currentPage == 1) {
return;
}
currentPage--;
startRow = (currentPage - 1) * pageSize;
}
/**
* 跳转到下一页
*/
public void next() {
if (currentPage < totalPages) {
currentPage++;
}
startRow = (currentPage - 1) * pageSize;
}
/**
* 跳转到尾页
*/
public void last() {
this.currentPage = totalPages;
if (currentPage < 1) {
currentPage = 1;
}
this.startRow = (currentPage - 1) * this.pageSize;
totalPages = (int) Math.ceil((double) totalRows / (double) this.pageSize);
}
/**
* 跳转到指定页
*
* @param currentPage 指定的页
*/
public void refresh(int currentPage) {
if (currentPage < 0) {
first();
}
if (currentPage > totalPages) {
last();
} else {
this.currentPage = currentPage;
this.startRow = (currentPage - 1) * this.pageSize;
}
}
public int getStartRow() {
return startRow;
}
public int getTotalPages() {
return totalPages;
}
public int getCurrentPage() {
return currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalRows() {
return totalRows;
}
}
关系数据库连接工具类
public class DBTool {
private static final int COMMIT_COUNT = 1;//10000;
private static String connectonUrl = "";
private static String userName = "";
private static String password = "";
public static void parseProperty(String fileName) throws IOException {
Properties pro = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(fileName);
pro.load(in);
connectonUrl = pro.getProperty("connectonUrl");
userName = pro.getProperty("userName");
password = pro.getProperty("password");
} catch (IOException e) {
throw e;
} finally {
try {
if (in != null)
in.close();
} catch (IOException e1) {
throw e1;
}
}
}
public static void executeSQL(String[] sql,Connection conn ) {
Statement st = null;
int index = 0;
try {
st = conn.createStatement();
int l = sql.length;
for (int i = 0; i < l; i++) {
st.addBatch(sql[i]);
if (i % COMMIT_COUNT == 0)
st.executeBatch();
index++;
}
st.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
System.out.println(sql[index]);
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public static Connection getConnection() {
String driverClsName = "com.mysql.jdbc.Driver";
Driver driver;
SimpleDriverDataSource sdd;
Connection conn = null;
try {
driver = (Driver) Class.forName(driverClsName).newInstance();
sdd = new SimpleDriverDataSource(driver, connectonUrl, userName, password);
conn = sdd.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static String getConnectonUrl() {
return connectonUrl;
}
public static void setConnectonUrl(String connectonUrl) {
DBTool.connectonUrl = connectonUrl;
}
public static String getUserName() {
return userName;
}
public static void setUserName(String userName) {
DBTool.userName = userName;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
DBTool.password = password;
}
}
Redis数据库连接
Mongo数据库连接
配置文件处理
有效性校验工具集合
/**
* 提供一些对象有效性校验的方法
*/
@SuppressWarnings("rawtypes")
public final class CheckUtil {
/**
* 判断字符串是否是符合指定格式的时间
* @param date 时间字符串
* @param format 时间格式
* @return 是否符合
*/
public final static boolean isDate(String date,String format){
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.parse(date);
return true;
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
/**
* 判断字符串有效性
*/
public final static boolean valid(String src) {
return !(src == null || "".equals(src.trim()));
}
/**
* 判断一组字符串是否有效
* @param src
* @return
*/
public final static boolean valid(String... src) {
for (String s : src) {
if (!valid(s)) {
return false;
}
}
return true;
}
/**
* 判断一个对象是否为空
*/
public final static boolean valid(Object obj) {
return !(null == obj);
}
/**
* 判断一组对象是否有效
* @param objs
* @return
*/
public final static boolean valid(Object... objs) {
if (objs != null && objs.length != 0) {
return true;
}
return false;
}
/**
* 判断集合的有效性
*/
public final static boolean valid(Collection col) {
return !(col == null || col.isEmpty());
}
/**
* 判断一组集合是否有效
* @param cols
* @return
*/
public final static boolean valid(Collection... cols) {
for (Collection c : cols) {
if (!valid(c)) {
return false;
}
}
return true;
}
/**
* 判断map是否有效
* @param map
* @return
*/
public final static boolean valid(Map map) {
return !(map == null || map.isEmpty());
}
/**
* 判断一组map是否有效
* @param maps 需要判断map
* @return 是否全部有效
*/
public final static boolean valid(Map... maps) {
for (Map m : maps) {
if (!valid(m)) {
return false;
}
}
return true;
}
}
文件相关工具类
/**
* 封装了些文件相关的操作
*/
public final class FileUtil {
/**
* Buffer的大小
*/
private static Integer BUFFER_SIZE = 1024 * 1024 * 10;
public static MessageDigest MD5 = null;
static {
try {
MD5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ne) {
ne.printStackTrace();
}
}
/**
* 获取文件的md5
*
* @param file
* @return
*/
public static String fileMD5(File file) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
return new BigInteger(1, MD5.digest()).toString(16);
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取文件的行数
*
* @param file 统计的文件
* @return 文件行数
*/
public final static int countLines(File file) {
try (LineNumberReader rf = new LineNumberReader(new FileReader(file))) {
long fileLength = file.length();
rf.skip(fileLength);
return rf.getLineNumber();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
/**
* 以列表的方式获取文件的所有行
*
* @param file 需要出来的文件
* @return 包含所有行的list
*/
public final static List<String> lines(File file) {
List<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 以列表的方式获取文件的所有行
*
* @param file 需要处理的文件
* @param encoding 指定读取文件的编码
* @return 包含所有行的list
*/
public final static List<String> lines(File file, String encoding) {
List<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 以列表的方式获取文件的指定的行数数据
*
* @param file 处理的文件
* @param lines 需要读取的行数
* @return 包含制定行的list
*/
public final static List<String> lines(File file, int lines) {
List<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
if (list.size() == lines) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 以列表的方式获取文件的指定的行数数据
*
* @param file 需要处理的函数
* @param lines 需要处理的行还俗
* @param encoding 指定读取文件的编码
* @return 包含制定行的list
*/
public final static List<String> lines(File file, int lines, String encoding) {
List<String> list = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding))) {
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
if (list.size() == lines) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 在文件末尾追加一行
*
* @param file 需要处理的文件
* @param str 添加的字符串
* @param encoding 指定写入的编码
* @return 是否成功
*/
public final static boolean appendLine(File file, String str, String encoding) {
String lineSeparator = System.getProperty("line.separator", "\n");
try (RandomAccessFile randomFile = new RandomAccessFile(file, "rw")) {
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.write((lineSeparator + str).getBytes(encoding));
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 将字符串写入到文件中
*/
public final static boolean write(File file, String str) {
try (RandomAccessFile randomFile = new RandomAccessFile(file, "rw")) {
randomFile.writeBytes(str);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 将字符串以追加的方式写入到文件中
*/
public final static boolean writeAppend(File file, String str) {
try (RandomAccessFile randomFile = new RandomAccessFile(file, "rw")) {
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.writeBytes(str);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 将字符串以制定的编码写入到文件中
*/
public final static boolean write(File file, String str, String encoding) {
try (RandomAccessFile randomFile = new RandomAccessFile(file, "rw")) {
randomFile.write(str.getBytes(encoding));
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 将字符串以追加的方式以制定的编码写入到文件中
*/
public final static boolean writeAppend(File file, String str, String encoding) {
try (RandomAccessFile randomFile = new RandomAccessFile(file, "rw")) {
long fileLength = randomFile.length();
randomFile.seek(fileLength);
randomFile.write(str.getBytes(encoding));
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 快速清空一个超大的文件
*
* @param file 需要处理的文件
* @return 是否成功
*/
public final static boolean cleanFile(File file) {
try (FileWriter fw = new FileWriter(file)) {
fw.write("");
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 获取文件最后的修改时间
*
* @param file 需要处理的文件
* @return 返回文件的修改时间
*/
public final static Date modifyTime(File file) {
return new Date(file.lastModified());
}
/**
* 复制文件
*
* @param resourcePath 源文件
* @param targetPath 目标文件
* @return 是否成功
*/
public final static boolean copy(String resourcePath, String targetPath) {
File file = new File(resourcePath);
return copy(file, targetPath);
}
/**
* 复制文件
* 通过该方式复制文件文件越大速度越是明显
*
* @param file 需要处理的文件
* @param targetFile 目标文件
* @return 是否成功
*/
public final static boolean copy(File file, String targetFile) {
try (FileInputStream fin = new FileInputStream(file);
FileOutputStream fout = new FileOutputStream(new File(targetFile))) {
FileChannel in = fin.getChannel();
FileChannel out = fout.getChannel();
//设定缓冲区
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
while (in.read(buffer) != -1) {
//准备写入,防止其他读取,锁住文件
buffer.flip();
out.write(buffer);
//准备读取。将缓冲区清理完毕,移动文件内部指针
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 创建多级目录
*
* @param paths 需要创建的目录
* @return 是否成功
*/
public final static boolean createPaths(String paths) {
File dir = new File(paths);
return !dir.exists() && dir.mkdir();
}
/**
* 创建文件支持多级目录
*
* @param filePath 需要创建的文件
* @return 是否成功
*/
public final static boolean createFiles(String filePath) {
File file = new File(filePath);
File dir = file.getParentFile();
if (!dir.exists()) {
if (dir.mkdirs()) {
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 删除一个文件
*
* @param file 需要处理的文件
* @return 是否成功
*/
public final static boolean deleteFile(File file) {
return file.delete();
}
/**
* 删除一个目录
*
* @param file 需要处理的文件
* @return 是否成功
*/
public final static boolean deleteDir(File file) {
List<File> files = listFileAll(file);
if (CheckUtil.valid(files)) {
for (File f : files) {
if (f.isDirectory()) {
deleteDir(f);
} else {
deleteFile(f);
}
}
}
return file.delete();
}
/**
* 快速的删除超大的文件
*
* @param file 需要处理的文件
* @return 是否成功
*/
public final static boolean deleteBigFile(File file) {
return cleanFile(file) && file.delete();
}
/**
* 复制目录
*
* @param filePath 需要处理的文件
* @param targetPath 目标文件
*/
public final static void copyDir(String filePath, String targetPath) {
File file = new File(filePath);
copyDir(file, targetPath);
}
/**
* 复制目录
*
* @param filePath 需要处理的文件
* @param targetPath 目标文件
*/
public final static void copyDir(File filePath, String targetPath) {
File targetFile = new File(targetPath);
if (!targetFile.exists()) {
createPaths(targetPath);
}
File[] files = filePath.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
String path = file.getName();
if (file.isDirectory()) {
copyDir(file, targetPath + "/" + path);
} else {
copy(file, targetPath + "/" + path);
}
}
}
}
/**
* 罗列指定路径下的全部文件
*
* @param path 需要处理的文件
* @return 包含所有文件的的list
*/
public final static List<File> listFile(String path) {
File file = new File(path);
return listFile(file);
}
/**
* 罗列指定路径下的全部文件
*
* @param path 需要处理的文件
* @param child 是否罗列子文件
* @return 包含所有文件的的list
*/
public final static List<File> listFile(String path, boolean child) {
return listFile(new File(path), child);
}
/**
* 罗列指定路径下的全部文件
*
* @param path 需要处理的文件
* @return 返回文件列表
*/
public final static List<File> listFile(File path) {
List<File> list = new ArrayList<>();
File[] files = path.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
if (file.isDirectory()) {
list.addAll(listFile(file));
} else {
list.add(file);
}
}
}
return list;
}
/**
* 罗列指定路径下的全部文件
*
* @param path 指定的路径
* @param child 是否罗列子目录
* @return
*/
public final static List<File> listFile(File path, boolean child) {
List<File> list = new ArrayList<>();
File[] files = path.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
if (child && file.isDirectory()) {
list.addAll(listFile(file));
} else {
list.add(file);
}
}
}
return list;
}
/**
* 罗列指定路径下的全部文件包括文件夹
*
* @param path 需要处理的文件
* @return 返回文件列表
*/
public final static List<File> listFileAll(File path) {
List<File> list = new ArrayList<>();
File[] files = path.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
list.add(file);
if (file.isDirectory()) {
list.addAll(listFileAll(file));
}
}
}
return list;
}
/**
* 罗列指定路径下的全部文件包括文件夹
*
* @param path 需要处理的文件
* @param filter 处理文件的filter
* @return 返回文件列表
*/
public final static List<File> listFileFilter(File path, FilenameFilter filter) {
List<File> list = new ArrayList<>();
File[] files = path.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
if (file.isDirectory()) {
list.addAll(listFileFilter(file, filter));
} else {
if (filter.accept(file.getParentFile(), file.getName())) {
list.add(file);
}
}
}
}
return list;
}
/**
* 获取指定目录下的特点文件,通过后缀名过滤
*
* @param dirPath 需要处理的文件
* @param postfixs 文件后缀
* @return 返回文件列表
*/
public final static List<File> listFileFilter(File dirPath, final String postfixs) {
/*
如果在当前目录中使用Filter讲只罗列当前目录下的文件不会罗列孙子目录下的文件
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(postfixs);
}
};
*/
List<File> list = new ArrayList<File>();
File[] files = dirPath.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
if (file.isDirectory()) {
list.addAll(listFileFilter(file, postfixs));
} else {
String fileName = file.getName().toLowerCase();
if (fileName.endsWith(postfixs.toLowerCase())) {
list.add(file);
}
}
}
}
return list;
}
/**
* 在指定的目录下搜寻文个文件
*
* @param dirPath 搜索的目录
* @param fileName 搜索的文件名
* @return 返回文件列表
*/
public final static List<File> searchFile(File dirPath, String fileName) {
List<File> list = new ArrayList<>();
File[] files = dirPath.listFiles();
if (CheckUtil.valid(files)) {
for (File file : files) {
if (file.isDirectory()) {
list.addAll(searchFile(file, fileName));
} else {
String Name = file.getName();
if (Name.equals(fileName)) {
list.add(file);
}
}
}
}
return list;
}
/**
* 获取文件后缀名
*
* @param file
* @return
*/
public final static String suffix(File file) {
String fileName = file.getName();
return fileName.substring(fileName.indexOf(".") + 1);
}
}
加密工具类
org.apache.commons.codec.digest.DigestUtils
- md5Hex MD5加密,返回32位
- sha1Hex SHA-1加密
- sha256Hex SHA-256加密
- sha512Hex SHA-512加密
- md5 MD5加密,返回16位
Class与反射工具类
/**
* <p>Java Class与反射相关的一些工具类</p>
*/
public class ClassUtil {
private static Logger logger = LoggerFactory.getLogger(ClassUtil.class);
/**
* 获取类加载器
*/
public static ClassLoader overridenClassLoader;
public static ClassLoader getContextClassLoader() {
return overridenClassLoader != null ? overridenClassLoader : Thread.currentThread().getContextClassLoader();
}
/**
* 获取指定类的全部属性字段
*
* @param className 需要获取的类名
* @param extendsField 是否获取接口或父类中的公共属性
* @return 属性字段数组
*/
public final static String[] getField(String className, boolean extendsField) {
Class classz = loadClass(className);
Field[] fields = classz.getFields();
Set<String> set = new HashSet<>();
if (fields != null) {
for (Field f : fields) {
set.add(f.getName());
}
}
if (extendsField) {
Field[] fieldz = classz.getDeclaredFields();
if (fieldz != null) {
for (Field f : fieldz) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取类中的公共属性
*
* @param className 需要获取的类名
* @param extendsField 是否获取接口或父类中的公共属性
* @return 属性字段数组
*/
public final static String[] getPublicField(String className, boolean extendsField) {
Class classz = loadClass(className);
Set<String> set = new HashSet<>();
Field[] fields = classz.getDeclaredFields();
if (fields != null) {
for (Field f : fields) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("public")) {
set.add(f.getName());
}
}
}
if (extendsField) {
Field[] fieldz = classz.getFields();
if (fieldz != null) {
for (Field f : fieldz) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取类中定义的protected类型的属性字段
*
* @param className 需要获取的类名
* @return protected类型的属性字段数组
*/
public final static String[] getProtectedField(String className) {
Class classz = loadClass(className);
Set<String> set = new HashSet<>();
Field[] fields = classz.getDeclaredFields();
if (fields != null) {
for (Field f : fields) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("protected")) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取类中定义的private类型的属性字段
*
* @param className 需要获取的类名
* @return private类型的属性字段数组
*/
public final static String[] getPrivateField(String className) {
Class classz = loadClass(className);
Set<String> set = new HashSet<>();
Field[] fields = classz.getDeclaredFields();
if (fields != null) {
for (Field f : fields) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("private")) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取对象的全部public类型方法
*
* @param className 需要获取的类名
* @param extendsMethod 是否获取继承来的方法
* @return 方法名数组
*/
public final static String[] getPublicMethod(String className, boolean extendsMethod) {
Class classz = loadClass(className);
Method[] methods;
if (extendsMethod) {
methods = classz.getMethods();
} else {
methods = classz.getDeclaredMethods();
}
Set<String> set = new HashSet<>();
if (methods != null) {
for (Method f : methods) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("public")) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取对象的全部protected类型方法
*
* @param className 需要获取的类名
* @param extendsMethod 是否获取继承来的方法
* @return 方法名数组
*/
public final static String[] getProtectedMethod(String className, boolean extendsMethod) {
Class classz = loadClass(className);
Method[] methods;
if (extendsMethod) {
methods = classz.getMethods();
} else {
methods = classz.getDeclaredMethods();
}
Set<String> set = new HashSet<>();
if (methods != null) {
for (Method f : methods) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("protected")) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取对象的全部private类型方法
*
* @param className 需要获取的类名
* @return 方法名数组
*/
public final static String[] getPrivateMethod(String className) {
Class classz = loadClass(className);
Method[] methods = classz.getDeclaredMethods();
Set<String> set = new HashSet<>();
if (methods != null) {
for (Method f : methods) {
String modifier = Modifier.toString(f.getModifiers());
if (modifier.startsWith("private")) {
set.add(f.getName());
}
}
}
return set.toArray(new String[set.size()]);
}
/**
* 获取对象的全部方法
*
* @param className 需要获取的类名
* @param extendsMethod 是否获取继承来的方法
* @return 方法名数组
*/
public final static String[] getMethod(String className, boolean extendsMethod) {
Class classz = loadClass(className);
Method[] methods;
if (extendsMethod) {
methods = classz.getMethods();
} else {
methods = classz.getDeclaredMethods();
}
Set<String> set = new HashSet<>();
if (methods != null) {
for (Method f : methods) {
set.add(f.getName());
}
}
return set.toArray(new String[set.size()]);
}
/**
* 调用对象的setter方法
*
* @param obj 对象
* @param att 属性名
* @param value 属性值
* @param type 属性类型
*/
public final static void setter(Object obj, String att, Object value, Class<?> type)
throws InvocationTargetException, IllegalAccessException {
try {
String name = att.substring(0, 1).toUpperCase() + att.substring(1);
Method met = obj.getClass().getMethod("set" + name, type);
met.invoke(obj, value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* 获取指定目录下所有的类名
*
* @param path 包名
* @param childPackage 是否获取子包
*/
public final static List<String> getClassName(String path, boolean childPackage) {
List<String> fileNames = new ArrayList<>();
if (path.endsWith(".jar")) {
fileNames.addAll(getClassNameByJar(path));
} else {
fileNames = getClassNameByFile(path, childPackage);
}
return fileNames;
}
/**
* 从项目文件获取某包下所有类
*
* @param filePath 文件路径
* @param childPackage 是否遍历子包
* @return 类的完整名称
*/
public final static List<String> getClassNameByFile(String filePath, boolean childPackage) {
List<String> myClassName = new ArrayList<>();
List<File> files = FileUtil.listFile(filePath, childPackage);
for (File file : files) {
if (file.getName().endsWith(".class")) {
String childFilePath = file.getPath();
int index = filePath.replaceAll("\\\\", ".").length();
childFilePath = childFilePath.replaceAll("\\\\", ".").substring(index, childFilePath.length());
myClassName.add(childFilePath);
}
}
return myClassName;
}
/**
* 从jar获取某包下所有类
*
* @param jarPath jar文件路径
* @return 类的完整名称
*/
public final static List<String> getClassNameByJar(String jarPath) {
List<String> myClassName = new ArrayList<>();
try (JarFile jarFile = new JarFile(jarPath)) {
Enumeration<JarEntry> entrys = jarFile.entries();
while (entrys.hasMoreElements()) {
JarEntry jarEntry = entrys.nextElement();
String entryName = jarEntry.getName();
if (entryName.endsWith(".class")) {
entryName = entryName.replace("/", ".").substring(0, entryName.lastIndexOf("."));
myClassName.add(entryName);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return myClassName;
}
/**
* 加载指定的类
*
* @param className 需要加载的类
* @return 加载后的类
*/
public final static Class loadClass(String className) {
Class theClass = null;
try {
theClass = Class.forName(className);
} catch (ClassNotFoundException e1) {
logger.error("load class error:" + e1.getMessage());
e1.printStackTrace();
}
return theClass;
}
/**
* 获取一个类的父类
*
* @param className 需要获取的类
* @return 父类的名称
*/
public final static String getSuperClass(String className) {
Class classz = loadClass(className);
Class superclass = classz.getSuperclass();
return superclass.getName();
}
/**
* 获取一个类的继承链
*
* @param className 需要获取的类
* @return 继承类名的数组
*/
public final static String[] getSuperClassChian(String className) {
Class classz = loadClass(className);
List<String> list = new ArrayList<>();
Class superclass = classz.getSuperclass();
String superName = superclass.getName();
if (!"java.lang.Object".equals(superName)) {
list.add(superName);
list.addAll(Arrays.asList(getSuperClassChian(superName)));
} else {
list.add(superName);
}
return list.toArray(new String[list.size()]);
}
/**
* 获取一类实现的全部接口
*
* @param className 需要获取的类
* @param extendsInterfaces 话说getInterfaces能全部获取到才对,然而测试的时候父类的接口并没有
* 因此就多除了这参数
* @return 实现接口名称的数组
*/
public final static String[] getInterfaces(String className, boolean extendsInterfaces) {
Class classz = loadClass(className);
List<String> list = new ArrayList<>();
Class[] interfaces = classz.getInterfaces();
if (interfaces != null) {
for (Class inter : interfaces) {
list.add(inter.getName());
}
}
if (extendsInterfaces) {
String[] superClass = getSuperClassChian(className);
for (String c : superClass) {
list.addAll(Arrays.asList(getInterfaces(c, false)));
}
}
return list.toArray(new String[list.size()]);
}
/**
* 将bean对象转换为Map对象
*
* @param obj
* @return
*/
public static Map convertObjToMap(Object obj) {
Map<String, Object> reMap = new HashMap<String, Object>();
if (obj == null) {
return null;
}
Field[] fields = obj.getClass().getDeclaredFields();
try {
for (int i = 0; i < fields.length; i++) {
try {
Field f = obj.getClass().getDeclaredField(fields[i].getName());
f.setAccessible(true);
Object o = f.get(obj);
reMap.put(fields[i].getName(), o);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
return reMap;
}
}
HDFS文件处理工具类
/**
* operate hdfs file or directory util class
*/
public class HdfsUtils {
public static final String HADOOP_CORE_SITE_FILE = "./config/cluster/hadoop/core-site.xml";
public static final String HADOOP_HDFS_SITE_FILE = "./config/cluster/hadoop/hdfs-site.xml";
public static final String KERBEROS_KRB5_CONF_FILE = "./config/kerberos/krb5.conf";
public static final String KERBEROS_KEYTAB_FILE = "./config/kerberos/hdfs.keytab";
/**
* make a new dir in the hdfs
*
* @param dir
* the dir may like '/tmp/testdir'
* @return boolean true-success, false-failed
* @exception IOException
* something wrong happends when operating files
*/
public static boolean mkdir(String hdfsUri, String dir) throws IOException {
if (StringUtils.isBlank(dir)) {
return false;
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
try {
fs = FileSystem.get(URI.create(dir), conf);
if (!fs.exists(new Path(dir))) {
fs.mkdirs(new Path(dir));
}
} finally {
if (fs != null) {
fs.close();
}
}
return true;
}
/**
* delete a dir in the hdfs. if dir not exists, it will throw
* FileNotFoundException
*
* @param dir
* the dir may like '/tmp/testdir'
* @return boolean true-success, false-failed
* @exception IOException
* something wrong happends when operating files
*
*/
public static boolean deleteDir(String hdfsUri, String dir) throws IOException {
if (StringUtils.isBlank(dir)) {
return false;
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
try {
fs = FileSystem.get(URI.create(dir), conf);
Path path = new Path(dir);
if (fs.exists(path)) {
fs.delete(path, true);
}
} finally {
if (fs != null) {
fs.close();
}
}
return true;
}
/**
* list files/directories/links names under a directory, not include embed
* objects
*
* @param dir
* a folder path may like '/tmp/testdir'
* @return List<String> list of file names
* @throws IOException
* file io exception
*/
public static List<String> listAll(String hdfsUri, String dir) throws IOException {
if (StringUtils.isBlank(dir)) {
return new ArrayList<String>();
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
List<String> names = new ArrayList<String>();
try {
fs = FileSystem.get(URI.create(dir), conf);
FileStatus[] stats = fs.listStatus(new Path(dir));
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
// regular file
names.add(stats[i].getPath().toString());
} else if (stats[i].isDirectory()) {
// dir
names.add(stats[i].getPath().toString());
} else if (stats[i].isSymlink()) {
// is s symlink in linux
names.add(stats[i].getPath().toString());
}
}
} finally {
if (fs != null) {
fs.close();
}
}
return names;
}
public static List<FileAttributes> listFileAttributes(String hdfsUri, String dir) throws IOException {
if (StringUtils.isBlank(dir)) {
return new ArrayList<FileAttributes>();
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
List<FileAttributes> files = new ArrayList<FileAttributes>();
try {
fs = FileSystem.get(URI.create(dir), conf);
FileStatus[] stats = fs.listStatus(new Path(dir));
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
// regular file
FileAttributes fileAttributes = new FileAttributes();
fileAttributes.setFilename(stats[i].getPath().getName().toString());
fileAttributes.setLength(stats[i].getLen());
fileAttributes.setModificationTime(stats[i].getModificationTime());
fileAttributes.setFiletype(stats[i].getGroup());
fileAttributes.setOwner(stats[i].getOwner());
files.add(fileAttributes);
}
}
} finally {
if (fs != null) {
fs.close();
}
}
return files;
}
public static List<String> listAllTimeDesc(String hdfsUri, String dir) throws IOException {
if (StringUtils.isBlank(dir)) {
return new ArrayList<String>();
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
List<String> names = new ArrayList<String>();
try {
fs = FileSystem.get(URI.create(dir), conf);
FileStatus[] stats = fs.listStatus(new Path(dir));
Collections.sort(Arrays.asList(stats), new Comparator<FileStatus>() {
@Override
public int compare(FileStatus o1, FileStatus o2) {
int time = Long.valueOf(o2.getModificationTime()).compareTo(Long.valueOf(o1.getModificationTime()));
if (0 == time) {
return o2.getPath().getName().compareTo(o1.getPath().getName());
}
return time;
}
});
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
// regular file
names.add(stats[i].getPath().toString());
} else if (stats[i].isDirectory()) {
// dir
names.add(stats[i].getPath().toString());
} else if (stats[i].isSymlink()) {
// is s symlink in linux
names.add(stats[i].getPath().toString());
}
}
} finally {
if (fs != null) {
fs.close();
}
}
return names;
}
/*
* upload the local file to the hds, notice that the path is full like
* /tmp/test.txt if local file not exists, it will throw a
* FileNotFoundException
*
* @param localFile local file path, may like F:/test.txt or
* /usr/local/test.txt
*
* @param hdfsFile hdfs file path, may like /tmp/dir
*
* @return boolean true-success, false-failed
*
* @throws IOException file io exception
*/
public static boolean uploadLocalFile2HDFS(String hdfsUri, String localFile, String hdfsFile) throws IOException {
if (StringUtils.isBlank(localFile) || StringUtils.isBlank(hdfsFile)) {
return false;
}
hdfsFile = hdfsUri + hdfsFile;
Configuration config = new Configuration();
FileSystem hdfs = null;
try {
hdfs = FileSystem.get(URI.create(hdfsUri), config);
Path src = new Path(localFile);
Path dst = new Path(hdfsFile);
hdfs.copyFromLocalFile(src, dst);
} finally {
if (hdfs != null) {
hdfs.close();
}
}
return true;
}
public static boolean uploadLocalFile2HDFS(boolean isKerberosEnable, String kerberosLoginUser,
String hdfsUri, String hdfsFile, InputStream inputStream)
throws IOException {
if (StringUtils.isBlank(hdfsFile)) {
return false;
}
Configuration config = new Configuration();
FileSystem hdfs = null;
try {
if (isKerberosEnable){
System.setProperty("java.security.krb5.conf", HdfsUtils.KERBEROS_KRB5_CONF_FILE);
config.set("hadoop.security.authentication","kerberos");
config.addResource(HdfsUtils.HADOOP_CORE_SITE_FILE);
config.addResource(HdfsUtils.HADOOP_HDFS_SITE_FILE);
UserGroupInformation.setConfiguration(config);
UserGroupInformation.loginUserFromKeytab(kerberosLoginUser, HdfsUtils.KERBEROS_KEYTAB_FILE);
UserGroupInformation userGroupInformation = UserGroupInformation.getLoginUser();
}
hdfs = FileSystem.get(URI.create(hdfsUri), config);
FSDataOutputStream outputStream = hdfs.create(new Path(hdfsFile), true);
IOUtils.copyBytes(inputStream, outputStream, 4096, true);
} finally {
if (hdfs != null) {
hdfs.close();
}
}
return true;
}
/*
* create a new file in the hdfs.
*
* notice that the toCreateFilePath is the full path
*
* and write the content to the hdfs file.
*/
/**
* create a new file in the hdfs. if dir not exists, it will create one
*
* @param newFile
* new file path, a full path name, may like '/tmp/test.txt'
* @param content
* file content
* @return boolean true-success, false-failed
* @throws IOException
* file io exception
*/
public static boolean createNewHDFSFile(String hdfsUri, String newFile, String content) throws IOException {
if (StringUtils.isBlank(newFile) || null == content) {
return false;
}
newFile = hdfsUri + newFile;
Configuration config = new Configuration();
FileSystem hdfs = null;
FSDataOutputStream os = null;大的
try {
hdfs = FileSystem.get(URI.create(newFile), config);
os.write(content.getBytes("UTF-8"));
} finally {
if (hdfs != null) {
hdfs.close();
}
if (os != null) {
os.close();
}
}
return true;
}
/**
* delete the hdfs file
*
* @param hdfsFile
* a full path name, may like '/tmp/test.txt'
* @return boolean true-success, false-failed
* @throws IOException
* file io exception
*/
public static boolean deleteHDFSFile(String hdfsUri, String hdfsFile) throws IOException {
if (StringUtils.isBlank(hdfsFile)) {
return false;
}
hdfsFile = hdfsUri + hdfsFile;
Configuration config = new Configuration();
FileSystem hdfs = null;
try {
hdfs = FileSystem.get(URI.create(hdfsFile), config);
Path path = new Path(hdfsFile);
return hdfs.delete(path, true);
} finally {
if (hdfs != null) {
hdfs.close();
}
}
}
/**
* If the name of hdfs's jar file is different from the new jar file ,
* delete the first
*
* @param hdfsUri
* @param dir
* @param jarFileName
* @throws IOException
*/
public static void deleteJarFile(boolean isKerberosEnable, String kerberosLoginUser,
String hdfsUri, String dir, String jarFileName) throws IOException {
if (StringUtils.isBlank(dir) || jarFileName == null) {
return;
}
dir = hdfsUri + dir;
Configuration conf = new Configuration();
FileSystem fs = null;
try {
fs = FileSystem.get(URI.create(dir), conf);
FileStatus[] stats = fs.listStatus(new Path(dir));
for (int i = 0; i < stats.length; ++i) {
if (stats[i].isFile()) {
String fileName = stats[i].getPath().getName().toString();
if (fileName.contains("jar") && (!fileName.equals(jarFileName))) {
Path path = new Path(dir + File.separator + fileName);
if (fs.exists(path)) {
fs.delete(path, true);
}
}
}
}
} finally {
if (fs != null) {
fs.close();
}
}
}
/**
* read the hdfs file content
*
* @param hdfsFile
* a full path name, may like '/tmp/test.txt'
* @return byte[] file content
* @throws IOException
* file io exception
*/
public static byte[] readHDFSFile(String hdfsUri, String hdfsFile) throws Exception {
if (StringUtils.isBlank(hdfsFile)) {
return null;
}
hdfsFile = hdfsUri + hdfsFile;
Configuration conf = new Configuration();
FileSystem fs = null;
FSDataInputStream is = null;
try {
fs = FileSystem.get(URI.create(hdfsFile), conf);
// check if the file exists
Path path = new Path(hdfsFile);
if (fs.exists(path)) {
is = fs.open(path);
// get the file info to create the buffer
FileStatus stat = fs.getFileStatus(path);
// create the buffer
byte[] buffer = new byte[Integer.parseInt(String.valueOf(stat.getLen()))];
is.readFully(0, buffer);
return buffer;
} else {
throw new Exception("the file is not found .");
}
} finally {
if (is != null) {
is.close();
}
if (fs != null) {
fs.close();
}
}
}
/**
* append something to file dst
*
* @param hdfsFile
* a full path name, may like '/tmp/test.txt'
* @param content
* string
* @return boolean true-success, false-failed
* @throws Exception
* something wrong
*/
public static boolean append(String hdfsUri, String hdfsFile, String content) throws Exception {
if (StringUtils.isBlank(hdfsFile)) {
return false;
}
if (StringUtils.isEmpty(content)) {
return true;
}
hdfsFile = hdfsUri + hdfsFile;
Configuration conf = new Configuration();
// solve the problem when appending at single datanode hadoop env
conf.set("dfs.client.block.write.replace-datanode-on-failure.policy", "NEVER");
conf.set("dfs.client.block.write.replace-datanode-on-failure.enable", "true");
FileSystem fs = FileSystem.get(URI.create(hdfsFile), conf);
InputStream in = null;
OutputStream out = null;
try {
// check if the file exists
Path path = new Path(hdfsFile);
if (fs.exists(path)) {
try {
in = new ByteArrayInputStream(content.getBytes());
out = fs.append(new Path(hdfsFile));
IOUtils.copyBytes(in, out, 4096, true);
} catch (Exception ex) {
fs.close();
throw ex;
}
} else {
HdfsUtils.createNewHDFSFile(hdfsUri, hdfsFile, content);
}
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (fs != null) {
fs.close();
}
}
return true;
}
}
读取Config文件工具类
public class PropertiesConfig {
/**
* 获取整个配置文件中的属性
* @param filePath 文件路径,即文件所在包的路径,例如:java/util/config.properties
*/
public static Properties readData(String filePath) {
filePath = getRealPath(filePath);
Properties props = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
in.close();
return props;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static String getRealPath(String filePath) {
//获取绝对路径 并截掉路径的”file:/“前缀
return PropertiesConfig.class.getResource("/" + filePath).toString().substring(6);
}
}
MD5编码工具类
/**
* MD5编码工具类
*
*/
public class MD5Code {
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0 };
private long[] state = new long[4];// state (ABCD)
private long[] count = new long[2];// number of bits, modulo 2^64 (lsb
// first)
private byte[] buffer = new byte[64]; // input buffer
public String digestHexStr;
private byte[] digest = new byte[16];
public String getMD5ofStr(String inbuf) {
md5Init();
md5Update(inbuf.getBytes(), inbuf.length());
md5Final();
digestHexStr = "";
for (int i = 0; i < 16; i++) {
digestHexStr += byteHEX(digest[i]);
}
return digestHexStr;
}
public MD5Code() {
md5Init();
return;
}
private void md5Init() {
count[0] = 0L;
count[1] = 0L;
// /* Load magic initialization constants.
state[0] = 0x67452301L;
state[1] = 0xefcdab89L;
state[2] = 0x98badcfeL;
state[3] = 0x10325476L;
return;
}
private long F(long x, long y, long z) {
return (x & y) | ((~x) & z);
}
private long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private long H(long x, long y, long z) {
return x ^ y ^ z;
}
private long I(long x, long y, long z) {
return y ^ (x | (~z));
}
private long FF(long a, long b, long c, long d, long x, long s, long ac) {
a += F(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long GG(long a, long b, long c, long d, long x, long s, long ac) {
a += G(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long HH(long a, long b, long c, long d, long x, long s, long ac) {
a += H(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private long II(long a, long b, long c, long d, long x, long s, long ac) {
a += I(b, c, d) + x + ac;
a = ((int) a << s) | ((int) a >>> (32 - s));
a += b;
return a;
}
private void md5Update(byte[] inbuf, int inputLen) {
int i, index, partLen;
byte[] block = new byte[64];
index = (int) (count[0] >>> 3) & 0x3F;
// /* Update number of bits */
if ((count[0] += (inputLen << 3)) < (inputLen << 3))
count[1]++;
count[1] += (inputLen >>> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (inputLen >= partLen) {
md5Memcpy(buffer, inbuf, index, 0, partLen);
md5Transform(buffer);
for (i = partLen; i + 63 < inputLen; i += 64) {
md5Memcpy(block, inbuf, 0, i, 64);
md5Transform(block);
}
index = 0;
} else
i = 0;
// /* Buffer remaining input */
md5Memcpy(buffer, inbuf, index, i, inputLen - i);
}
private void md5Final() {
byte[] bits = new byte[8];
int index, padLen;
// /* Save number of bits */
Encode(bits, count, 8);
// /* Pad out to 56 mod 64.
index = (int) (count[0] >>> 3) & 0x3f;
padLen = (index < 56) ? (56 - index) : (120 - index);
md5Update(PADDING, padLen);
// /* Append length (before padding) */
md5Update(bits, 8);
// /* Store state in digest */
Encode(digest, state, 16);
}
private void md5Memcpy(byte[] output, byte[] input, int outpos, int inpos,
int len) {
int i;
for (i = 0; i < len; i++)
output[outpos + i] = input[inpos + i];
}
private void md5Transform(byte block[]) {
long a = state[0], b = state[1], c = state[2], d = state[3];
long[] x = new long[16];
Decode(x, block, 64);
/* Round 1 */
a = FF(a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */
d = FF(d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */
c = FF(c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */
b = FF(b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */
a = FF(a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */
d = FF(d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */
c = FF(c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */
b = FF(b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */
a = FF(a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */
d = FF(d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */
c = FF(c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */
b = FF(b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */
a = FF(a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */
d = FF(d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */
c = FF(c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */
b = FF(b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */
d = GG(d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */
c = GG(c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */
b = GG(b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG(a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */
d = GG(d, a, b, c, x[10], S22, 0x2441453L); /* 22 */
c = GG(c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */
b = GG(b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG(a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */
d = GG(d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */
c = GG(c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */
b = GG(b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */
a = GG(a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */
d = GG(d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */
c = GG(c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */
b = GG(b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */
d = HH(d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */
c = HH(c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */
b = HH(b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */
a = HH(a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */
d = HH(d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */
c = HH(c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */
b = HH(b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */
a = HH(a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */
d = HH(d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */
c = HH(c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */
b = HH(b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */
a = HH(a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */
d = HH(d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */
c = HH(c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */
b = HH(b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */
d = II(d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */
c = II(c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */
b = II(b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */
a = II(a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */
d = II(d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */
c = II(c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */
b = II(b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */
a = II(a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */
d = II(d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */
c = II(c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */
b = II(b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */
a = II(a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */
d = II(d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */
c = II(c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */
b = II(b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
private void Encode(byte[] output, long[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4) {
output[j] = (byte) (input[i] & 0xffL);
output[j + 1] = (byte) ((input[i] >>> 8) & 0xffL);
output[j + 2] = (byte) ((input[i] >>> 16) & 0xffL);
output[j + 3] = (byte) ((input[i] >>> 24) & 0xffL);
}
}
private void Decode(long[] output, byte[] input, int len) {
int i, j;
for (i = 0, j = 0; j < len; i++, j += 4)
output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8)
| (b2iu(input[j + 2]) << 16) | (b2iu(input[j + 3]) << 24);
return;
}
public static long b2iu(byte b) {
return b < 0 ? b & 0x7F + 128 : b;
}
public static String byteHEX(byte ib) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
char[] ob = new char[2];
ob[0] = Digit[(ib >>> 4) & 0X0F];
ob[1] = Digit[ib & 0X0F];
String s = new String(ob);
return s;
}
}
邮件发送
package com.zqykj.simulate.city.demo.util;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 功能概要:邮件发送工具类
*/
public class MailSendUtil {
private static Logger logger = LoggerFactory.getLogger(MailSendUtil.class);
private MimeMessage mimeMsg; // MIME邮件对象
private Session session; // 邮件会话对象
private Properties props; // 系统属性
private boolean needAuth = false; // smtp是否需要认证
private String username; // smtp认证用户名
private String password; // smtp认证用户密码
private Multipart mp; // 含标题,邮件内容,附件
/**
* Constructor
*
* @param smtp 邮件发送服务器
*/
public MailSendUtil(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
}
/**
* 设置邮件发送服务器
*
* @param hostName String
*/
public void setSmtpHost(String hostName) {
logger.info("设置系统属性:mail.smtp.host = " + hostName);
if (props == null) {
props = System.getProperties(); // 获得系统属性对象
}
props.put("mail.smtp.host", hostName); // 设置SMTP主机
}
/**
* 创建MIME邮件对象
*
* @return
*/
public boolean createMimeMessage() {
try {
logger.info("准备获取邮件会话对象!");
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});// 获得邮件会话对象
} catch (Exception e) {
logger.error("获取邮件会话对象时发生错误!" + e);
return false;
}
logger.info("准备创建MIME邮件对象!");
try {
mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch (Exception e) {
logger.error("创建MIME邮件对象失败!" + e);
return false;
}
}
/**
* 设置SMTP是否需要验证
*
* @param need
*/
public void setNeedAuth(boolean need) {
logger.info("设置smtp身份认证:mail.smtp.auth = " + need);
if (props == null) {
props = System.getProperties();
}
if (need) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
}
/**
* 设置用户名和密码
*
* @param name
* @param pass
*/
public void setNamePass(String name, String pass) {
username = name;
password = pass;
}
/**
* 设置邮件主题
*
* @param mailSubject
* @return
*/
public boolean setSubject(String mailSubject) {
logger.info("设置邮件主题!");
try {
mimeMsg.setSubject(mailSubject);
return true;
} catch (Exception e) {
logger.error("设置邮件主题发生错误!");
return false;
}
}
/**
* 设置邮件正文
*
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try {
BodyPart bp = new MimeBodyPart();
bp.setContent("" + mailBody, "text/html;charset=GBK");
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
logger.error("设置邮件正文时发生错误!" + e);
return false;
}
}
/**
* 添加附件
*
* @param filename String
*/
public boolean addFileAffix(String filename) {
if (filename == null) {
return true;
}
logger.info("增加邮件附件:" + filename);
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(MimeUtility.encodeText(fileds.getName()));
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
logger.error("增加邮件附件:" + filename + "发生错误!" + e);
return false;
}
}
/**
* 设置发信人
*
* @param from String
*/
public boolean setFrom(String from) {
logger.info("设置发信人!");
try {
mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
return true;
} catch (Exception e) {
return false;
}
}
/**
* 设置收信人
*
* @param to String
*/
public boolean setTo(String to) {
logger.info("设置收件人:" + to);
if (to == null) {
return false;
}
try {
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
return true;
} catch (Exception e) {
return false;
}
}
/**
* 设置抄送人
*
* @param copyto String
*/
public boolean setCopyTo(String copyto) {
if (copyto == null) {
return false;
}
try {
mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto));
return true;
} catch (Exception e) {
return false;
}
}
/**
* 发送邮件
*/
public boolean sendOut() {
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
logger.info("正在发送邮件....");
Transport transport = session.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"), username, password);
transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
// transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
// Transport.send(mimeMsg);
logger.info("发送邮件成功!");
transport.close();
return true;
} catch (Exception e) {
logger.error("邮件发送失败!" + e);
return false;
}
}
/**
* 调用sendOut方法完成邮件发送
*
* @param smtp
* @param from
* @param to
* @param subject
* @param content
* @param username
* @param password
* @return boolean
*/
public static boolean send(String smtp, String from, String to, String subject, String content, String username,
String password) {
MailSendUtil theMail = new MailSendUtil(smtp);
theMail.setNeedAuth(true); // 需要验证
if (!theMail.setSubject(subject)) {
return false;
}
if (!theMail.setBody(content)) {
return false;
}
if (!theMail.setTo(to)) {
return false;
}
if (!theMail.setFrom(from)) {
return false;
}
theMail.setNamePass(username, password);
if (!theMail.sendOut()) {
return false;
}
return true;
}
/**
* 调用sendOut方法完成邮件发送,带抄送
*
* @param smtp
* @param from
* @param to
* @param copyto
* @param subject
* @param content
* @param username
* @param password
* @return boolean
*/
public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content,
String username, String password) {
MailSendUtil theMail = new MailSendUtil(smtp);
theMail.setNeedAuth(true); // 需要验证
if (!theMail.setSubject(subject)) {
return false;
}
if (!theMail.setBody(content)) {
return false;
}
if (!theMail.setTo(to)) {
return false;
}
if (!theMail.setCopyTo(copyto)) {
return false;
}
if (!theMail.setFrom(from)) {
return false;
}
theMail.setNamePass(username, password);
if (!theMail.sendOut())
return false;
return true;
}
/**
* 调用sendOut方法完成邮件发送,带附件
*
* @param smtp
* @param from
* @param to
* @param subject
* @param content
* @param username
* @param password
* @param filename 附件路径
* @return
*/
public static boolean send(String smtp, String from, String to, String subject, String content, String username,
String password, String filename) {
MailSendUtil theMail = new MailSendUtil(smtp);
theMail.setNeedAuth(true); // 需要验证
logger.info("发送邮件至:{} " + to);
if (!theMail.setSubject(subject)) {
return false;
}
if (!theMail.setBody(content)) {
return false;
}
if (!theMail.addFileAffix(filename)) {
return false;
}
if (!theMail.setTo(to)) {
return false;
}
if (!theMail.setFrom(from)) {
return false;
}
theMail.setNamePass(username, password);
if (!theMail.sendOut()) {
return false;
}
return true;
}
/**
* 调用sendOut方法完成邮件发送,带附件和抄送
*
* @param smtp
* @param from
* @param to
* @param copyto
* @param subject
* @param content
* @param username
* @param password
* @param filename
* @return
*/
public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content,
String username, String password, String filename) {
MailSendUtil theMail = new MailSendUtil(smtp);
theMail.setNeedAuth(true); // 需要验证
if (!theMail.setSubject(subject)) {
return false;
}
if (!theMail.setBody(content)) {
return false;
}
if (!theMail.addFileAffix(filename)) {
return false;
}
if (!theMail.setTo(to)) {
return false;
}
if (!theMail.setCopyTo(copyto)) {
return false;
}
if (!theMail.setFrom(from)) {
return false;
}
theMail.setNamePass(username, password);
if (!theMail.sendOut()) {
return false;
}
return true;
}
public static void main(String[] args) {
String smtp = "10.75.210.10";
String from = "test1@xxxxx";
String to = "xxx@xxxx";
String subject = "管理系统";
String content = "邮件内容";
String username = "test1";
String password = "Password1";
String filename = "D:\\file\\ces\\INT_MMS_SETTLE_20150211_0001.DATA";
try {
MailSendUtil.send(smtp, from, to, subject, content, username, password, filename);
} catch (Exception e) {
e.printStackTrace();
}
}
}
工具类源码集合:https://github.com/calm4wei/opslabJutil