- 浏览: 155912 次
- 性别:
- 来自: 沈阳
文章分类
最新评论
-
cuishuangjia:
文本格式的肯定没问题二进制的,没测试过
Penguins DbTools数据库管理移植差分工具(EXCEL相关) ver 20160530 -
mfkvfn:
能处理clob或blob数据么?
Penguins DbTools数据库管理移植差分工具(EXCEL相关) ver 20160530 -
cuishuangjia:
longware 写道看介绍功能貌似很强大,但是软件没法用,U ...
数据库管理移植工具(EXCEL相关) ver 20140627 -
longware:
看介绍功能貌似很强大,但是软件没法用,UI功能太乱,根本不符合 ...
数据库管理移植工具(EXCEL相关) ver 20140627 -
longware:
good,java写的,用exe4j包装的
数据库管理移植工具(EXCEL相关) ver 20140627
-------C:\aa\common\CmnDateParse.java
/**
*
*/
package org.mydbsee.common;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
/**
* @author Think
*
*/
public class CmnDateParse {
private SimpleDateFormat fmt = null;
private ParsePosition pos = null;
/**
* @return the fmt
*/
public SimpleDateFormat getFmt() {
return fmt;
}
/**
* @param fmt the fmt to set
*/
public void setFmt(SimpleDateFormat fmt) {
this.fmt = fmt;
}
/**
* @return the pos
*/
public ParsePosition getPos() {
return pos;
}
/**
* @param pos the pos to set
*/
public void setPos(ParsePosition pos) {
this.pos = pos;
}
}
-------C:\aa\common\CmnDateUtil.java
/*
* @(#) 所有版权归聚灵工作室所有.
*
* $Id$
*
* ===================================
* Electric Operation Maintenance System(EOMS)
*
* Copyright (c) 2006 by INSPUR LG, Inc.
* All rights reserved.
*/
package org.mydbsee.common;
import java.io.Serializable;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
/**
* 日期操作工具类,主要实现了日期的常用操作。
* <p>
* 在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式.
* <p>
* 格式的意义如下: 日期和时间模式 <br>
* 日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z'
* 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''"
* 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。
* <p>
* 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留): <br>
* <table>
* <tr>
* <td>字母</td>
* <td>日期或时间元素</td>
* <td>表示</td>
* <td>示例</td>
* <td>
* </tr>
* <tr>
* <td>G</td>
* <td>Era</td>
* <td>标志符</td>
* <td>Text</td>
* <td>AD</td>
* <td>
* </tr>
* <tr>
* <td>y</td>
* <td>年</td>
* <td>Year</td>
* <td>1996;</td>
* <td>96</td>
* <td>
* </tr>
* <tr>
* <td>M</td>
* <td>年中的月份</td>
* <td>Month</td>
* <td>July;</td>
* <td>Jul;</td>
* <td>07
* </tr>
* <tr>
* <td>w</td>
* <td>年中的周数</td>
* <td>Number</td>
* <td>27</td>
* <td>
* </tr>
* <tr>
* <td>W</td>
* <td>月份中的周数</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>D</td>
* <td>年中的天数</td>
* <td>Number</td>
* <td>189</td>
* <td>
* </tr>
* <tr>
* <td>d</td>
* <td>月份中的天数</td>
* <td>Number</td>
* <td>10</td>
* <td>
* </tr>
* <tr>
* <td>F</td>
* <td>月份中的星期</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>E</td>
* <td>星期中的天数</td>
* <td>Text</td>
* <td>Tuesday;</td>
* <td>Tue
* </tr>
* <tr>
* <td>a</td>
* <td>Am/pm</td>
* <td>标记</td>
* <td>Text</td>
* <td>PM</td>
* <td>
* </tr>
* <tr>
* <td>H</td>
* <td>一天中的小时数(0-23)</td>
* <td>Number</td>
* <td>0
* </tr>
* <tr>
* <td>k</td>
* <td>一天中的小时数(1-24)</td>
* <td>Number</td>
* <td>24</td>
* <td>
* </tr>
* <tr>
* <td>K</td>
* <td>am/pm</td>
* <td>中的小时数(0-11)</td>
* <td>Number</td>
* <td>0</td>
* <td>
* </tr>
* <tr>
* <td>h</td>
* <td>am/pm</td>
* <td>中的小时数(1-12)</td>
* <td>Number</td>
* <td>12</td>
* <td>
* </tr>
* <tr>
* <td>m</td>
* <td>小时中的分钟数</td>
* <td>Number</td>
* <td>30</td>
* <td>
* </tr>
* <tr>
* <td>s</td>
* <td>分钟中的秒数</td>
* <td>Number</td>
* <td>55</td>
* <td>
* </tr>
* <tr>
* <td>S</td>
* <td>毫秒数</td>
* <td>Number</td>
* <td>978</td>
* <td>
* </tr>
* <tr>
* <td>z</td>
* <td>时区</td>
* <td>General</td>
* <td>time</td>
* <td>zone</td>
* <td>Pacific</td>
* <td>Standard</td>
* <td>Time;</td>
* <td>PST;</td>
* <td>GMT-08:00
* </tr>
* <tr>
* <td>Z</td>
* <td>时区</td>
* <td>RFC</td>
* <td>822</td>
* <td>time</td>
* <td>zone</td>
* <td>-0800</td>
* <td>
* </tr>
* </table>
*
* 模式字母通常是重复的,其数量确定其精确表示:
*
*/
public final class CmnDateUtil implements Serializable {
private static final long serialVersionUID = -3098985139095632110L;
private static Map<String,CmnDateParse> dateParseMap = new HashMap<String, CmnDateParse>();
private CmnDateUtil() {
}
public static void main(String[] args) {
// System.out.println(getYearByDate(new Date()));
System.out.println(getYMDhms6(new Date()));
}
public static List<Integer> getYMDhms6(Date date) {
List<Integer> lst = new ArrayList<Integer>();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
lst.add(cal.get(Calendar.YEAR));
lst.add(cal.get(Calendar.MONTH));
lst.add(cal.get(Calendar.DAY_OF_MONTH)+1);
lst.add(cal.get(Calendar.HOUR_OF_DAY));
lst.add(cal.get(Calendar.MINUTE));
lst.add(cal.get(Calendar.SECOND));
return lst;
}
public static String getYearByDate(Date date) {
return String.valueOf(getYMDhms6(date).get(0));
}
/**
* 格式化日期显示格式
*
* @param sdate
* 原始日期格式 s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象
* @param format
* 格式化后日期格式
* @return 格式化后的日期显示
*/
public static String dateFormat(String sdate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
java.sql.Date date = java.sql.Date.valueOf(sdate);
String dateString = formatter.format(date);
return dateString;
}
/**
* 求两个日期相差天数
*
* @param sd
* 起始日期,格式yyyy-MM-dd
* @param ed
* 终止日期,格式yyyy-MM-dd
* @return 两个日期相差天数
*/
public static long getIntervalDays(String sd, String ed) {
return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date.valueOf(sd)).getTime()) / (3600 * 24 * 1000);
}
/**
* 起始年月yyyy-MM与终止月yyyy-MM之间跨度的月数。
*
* @param beginMonth
* 格式为yyyy-MM
* @param endMonth
* 格式为yyyy-MM
* @return 整数。
*/
public static int getInterval(String beginMonth, String endMonth) {
int intBeginYear = Integer.parseInt(beginMonth.substring(0, 4));
int intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth.indexOf("-") + 1));
int intEndYear = Integer.parseInt(endMonth.substring(0, 4));
int intEndMonth = Integer.parseInt(endMonth.substring(endMonth.indexOf("-") + 1));
return ((intEndYear - intBeginYear) * 12) + (intEndMonth - intBeginMonth) + 1;
}
public static boolean checkDate(String sDate, String dateFormat)throws Throwable {
Date date = getDate(sDate, dateFormat);
if (date == null) {
return false;
}
String str = getFormatDateTime(date, dateFormat);
if (!CmnStrUtils.isEqual(str, sDate)) {
return false;
}
return true;
}
/**
* 根据给定的分析位置开始分析日期/时间字符串。例如,时间文本 "07/10/96 4:5 PM, PDT" 会分析成等同于
* Date(837039928046) 的 Date。
*
* @param sDate
* @param dateFormat
* @return
* @throws Throwable
*/
public static Date getDate(String sDate, String dateFormat) throws Throwable{
CmnDateParse csjDateParse = dateParseMap.get(dateFormat);
SimpleDateFormat fmt = null;
ParsePosition pos = null;
if (csjDateParse == null) {
fmt = new SimpleDateFormat(dateFormat);
pos = new ParsePosition(0);
dateParseMap.put(sDate, csjDateParse);
} else {
fmt = csjDateParse.getFmt();
pos = csjDateParse.getPos();
}
return fmt.parse(sDate, pos);
}
/**
* 取得当前日期的年份,以yyyy格式返回.
*
* @return 当年 yyyy
*/
public static String getCurrentYear()throws Throwable {
return getFormatCurrentTime("yyyy");
}
/**
* 自动返回上一年。例如当前年份是2007年,那么就自动返回2006
*
* @return 返回结果的格式为 yyyy
*/
public static String getBeforeYear()throws Throwable {
String currentYear = getFormatCurrentTime("yyyy");
int beforeYear = Integer.parseInt(currentYear) - 1;
return "" + beforeYear;
}
/**
* 取得当前日期的月份,以MM格式返回.
*
* @return 当前月份 MM
*/
public static String getCurrentMonth()throws Throwable {
return getFormatCurrentTime("MM");
}
/**
* 取得当前日期的天数,以格式"dd"返回.
*
* @return 当前月中的某天dd
*/
public static String getCurrentDay()throws Throwable {
return getFormatCurrentTime("dd");
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentDate() throws Throwable{
return getFormatDateTime(new Date(), "yyyy-MM-dd");
}
/**
* 返回当前指定的时间戳。格式为yyyy-MM-dd HH:mm:ss
*
* @return 格式为yyyy-MM-dd HH:mm:ss,总共19位。
*/
public static String getCurrentDateTime() throws Throwable{
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatDate(Date date)throws Throwable {
return getFormatDateTime(date, "yyyy-MM-dd");
}
/**
* 根据制定的格式,返回日期字符串。例如2007-05-05
*
* @param format
* "yyyy-MM-dd" 或者 "yyyy/MM/dd",当然也可以是别的形式。
* @return 指定格式的日期字符串。
*/
public static String getFormatDate(String format)throws Throwable {
return getFormatDateTime(new Date(), format);
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentTime()throws Throwable {
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatTime(Date date)throws Throwable {
return getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 根据给定的格式,返回时间字符串。
* <p>
* 格式参照类描绘中说明.和方法getFormatDate是一样的。
*
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatCurrentTime(String format)throws Throwable {
return getFormatDateTime(new Date(), format);
}
/**
* 根据给定的格式与时间(Date类型的),返回时间字符串。最为通用。<br>
*
* @param date
* 指定的日期
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatDateTime(Date date, String format) throws Throwable{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* 取得指定年月日的日期对象.
*
* @param year
* 年
* @param month
* 月注意是从1到12
* @param day
* 日
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(int year, int month, int day) {
Calendar c = new GregorianCalendar();
c.set(year, month - 1, day);
return c.getTime();
}
/**
* 获取指定日期的下一天。
*
* @param date
* yyyy/MM/dd
* @return yyyy/MM/dd
*/
public static String getDateTomorrow(String date)throws Throwable {
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, 1);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 获取与指定日期相差指定天数的日期。
*
* @param date
* yyyy/MM/dd
* @param offset
* 正整数
* @return yyyy/MM/dd
*/
public static String getDateOffset(String date, int offset)throws Throwable {
// Date tempDate = getDateObj(date, "[/]");
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, offset);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 取得指定分隔符分割的年月日的日期对象.
*
* @param argsDate
* 格式为"yyyy-MM-dd"
* @param split
* 时间格式的间隔符,例如“-”,“/”,要和时间一致起来。
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(String argsDate, String split) {
String[] temp = argsDate.split(split);
int year = new Integer(temp[0]).intValue();
int month = new Integer(temp[1]).intValue();
int day = new Integer(temp[2]).intValue();
return getDateObj(year, month, day);
}
/**
* 取得给定字符串描述的日期对象,描述模式采用pattern指定的格式.
*
* @param dateStr
* 日期描述 从给定字符串的开始分析文本,以生成一个日期。该方法不使用给定字符串的整个文本。 有关日期分析的更多信息,请参阅
* parse(String, ParsePosition) 方法。一个 String,应从其开始处进行分析
*
* @param pattern
* 日期模式
* @return 给定字符串描述的日期对象。
*/
public static Date getDateFromString(String dateStr, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date resDate = null;
try {
resDate = sdf.parse(dateStr);
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return resDate;
}
/**
* 取得当前Date对象.
*
* @return Date 当前Date对象.
*/
public static Date getDateObj() {
Calendar c = new GregorianCalendar();
return c.getTime();
}
/**
*
* @return 当前月份有多少天;
*/
public static int getDaysOfCurMonth()throws Throwable {
int curyear = new Integer(getCurrentYear()).intValue(); // 当前年份
int curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static int getDaysOfMonth(final String time) {
if (time.length() != 6) {
throw new NullPointerException("参数的格式必须是yyyyMM");
}
String[] timeArray = time.split("-");
int curyear = new Integer(time.substring(0, 4)); // 当前年份
int curMonth = new Integer(time.substring(4, 6));// 当前月份
if (curMonth > 12) {
throw new NullPointerException("参数的格式必须是yyyyMM,而且月份必须小于等于12。");
}
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
if (curMonth == 12) {
return mArray[0];
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static String getLastDayOfMonth(final String yyyy, final String MM) {
int days = getDaysOfMonth(yyyy+MM);
return yyyy + MM +String.valueOf(days);
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static String getFirstDayOfMonth(final String yyyy, final String MM) {
return yyyy + MM + "01";
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 返回指定为年度为year月度month的月份内,第weekOfMonth个星期的第dayOfWeek天是当月的几号。<br>
* 00 00 00 01 02 03 04 <br>
* 05 06 07 08 09 10 11<br>
* 12 13 14 15 16 17 18<br>
* 19 20 21 22 23 24 25<br>
* 26 27 28 29 30 31 <br>
* 2006年的第一个周的1到7天为:05 06 07 01 02 03 04 <br>
* 2006年的第二个周的1到7天为:12 13 14 08 09 10 11 <br>
* 2006年的第三个周的1到7天为:19 20 21 15 16 17 18 <br>
* 2006年的第四个周的1到7天为:26 27 28 22 23 24 25 <br>
* 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。
*
* @param year
* 形式为yyyy <br>
* @param month
* 形式为MM,参数值在[1-12]。<br>
* @param weekOfMonth
* 在[1-6],因为一个月最多有6个周。<br>
* @param dayOfWeek
* 数字在1到7之间,包括1和7。1表示星期天,7表示星期六<br>
* -6为星期日-1为星期五,0为星期六 <br>
* @return <type>int</type>
*/
public static int getDayofWeekInMonth(String year, String month, String weekOfMonth, String dayOfWeek) {
Calendar cal = new GregorianCalendar();
// 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
int y = new Integer(year).intValue();
int m = new Integer(month).intValue();
cal.clear();// 不保留以前的设置
cal.set(y, m - 1, 1);// 将日期设置为本月的第一天。
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, new Integer(weekOfMonth).intValue());
cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());
// System.out.print(cal.get(Calendar.MONTH)+" ");
// System.out.print("当"+cal.get(Calendar.WEEK_OF_MONTH)+"\t");
// WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 根据指定的年月日小时分秒,返回一个java.Util.Date对象。
*
* @param year
* 年
* @param month
* 月 0-11
* @param date
* 日
* @param hourOfDay
* 小时 0-23
* @param minute
* 分 0-59
* @param second
* 秒 0-59
* @return 一个Date对象。
*/
public static Date getDate(int year, int month, int date, int hourOfDay, int minute, int second) {
Calendar cal = new GregorianCalendar();
cal.set(year, month, date, hourOfDay, minute, second);
return cal.getTime();
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param year
* @param month
* month是从1开始的12结束
* @param day
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String year, String month, String day) {
Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1,
new Integer(day).intValue());
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
* "yyyy/MM/dd",或者"yyyy-MM-dd"
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String date) {
String[] temp = null;
if (date.indexOf("/") > 0) {
temp = date.split("/");
}
if (date.indexOf("-") > 0) {
temp = date.split("-");
}
return getDayOfWeek(temp[0], temp[1], temp[2]);
}
/**
* 返回当前日期是星期几。例如:星期日、星期一、星期六等等。
*
* @param date
* 格式为 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 返回当前日期是星期几
*/
public static String getChinaDayOfWeek(String date) {
String[] weeks = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
int week = getDayOfWeek(date);
return weeks[week - 1];
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
*
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 返回制定日期所在的周是一年中的第几个周。<br>
* created by wangmj at 20060324.<br>
*
* @param year
* @param month
* 范围1-12<br>
* @param day
* @return int
*/
public static int getWeekOfYear(String year, String month, String day) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @return Date 加上一定天数以后的Date对象.
*/
public static Date getDateAdd(Date date, int amount) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return cal.getTime();
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @param format
* 输出格式.
* @return Date 加上一定天数以后的Date对象.
*/
public static String getFormatDateAdd(Date date, int amount, String format)throws Throwable {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return getFormatDateTime(cal.getTime(), format);
}
/**
* 获得当前日期固定间隔天数的日期,如前60天dateAdd(-60)
*
* @param amount
* 距今天的间隔日期长度,向前为负,向后为正
* @param format
* 输出日期的格式.
* @return java.lang.String 按照格式输出的间隔的日期字符串.
*/
public static String getFormatCurrentAdd(int amount, String format)throws Throwable {
Date d = getDateAdd(new Date(), amount);
return getFormatDateTime(d, format);
}
/**
* 取得给定格式的昨天的日期输出
*
* @param format
* 日期输出的格式
* @return String 给定格式的日期字符串.
*/
public static String getFormatYestoday(String format)throws Throwable {
return getFormatCurrentAdd(-1, format);
}
/**
* 返回指定日期的前一天。<br>
*
* @param sourceDate
* @param format
* yyyy MM dd hh mm ss
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getYestoday(String sourceDate, String format)throws Throwable {
return getFormatDateAdd(getDateFromString(sourceDate, format), -1, format);
}
/**
* 返回明天的日期,<br>
*
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatTomorrow(String format)throws Throwable {
return getFormatCurrentAdd(1, format);
}
/**
* 返回指定日期的后一天。<br>
*
* @param sourceDate
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatDateTommorrow(String sourceDate, String format)throws Throwable {
return getFormatDateAdd(getDateFromString(sourceDate, format), 1, format);
}
/**
* 根据主机的默认 TimeZone,来获得指定形式的时间字符串。
*
* @param dateFormat
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getCurrentDateString(String dateFormat) {
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(cal.getTime());
}
// /**
// * @deprecated 不鼓励使用。 返回当前时间串 格式:yyMMddhhmmss,在上传附件时使用
// *
// * @return String
// */
// public static String getCurDate() {
// GregorianCalendar gcDate = new GregorianCalendar();
// int year = gcDate.get(GregorianCalendar.YEAR);
// int month = gcDate.get(GregorianCalendar.MONTH) + 1;
// int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);
// int hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY);
// int minute = gcDate.get(GregorianCalendar.MINUTE);
// int sen = gcDate.get(GregorianCalendar.SECOND);
// String y;
// String m;
// String d;
// String h;
// String n;
// String s;
// y = new Integer(year).toString();
//
// if (month < 10) {
// m = "0" + new Integer(month).toString();
// } else {
// m = new Integer(month).toString();
// }
//
// if (day < 10) {
// d = "0" + new Integer(day).toString();
// } else {
// d = new Integer(day).toString();
// }
//
// if (hour < 10) {
// h = "0" + new Integer(hour).toString();
// } else {
// h = new Integer(hour).toString();
// }
//
// if (minute < 10) {
// n = "0" + new Integer(minute).toString();
// } else {
// n = new Integer(minute).toString();
// }
//
// if (sen < 10) {
// s = "0" + new Integer(sen).toString();
// } else {
// s = new Integer(sen).toString();
// }
//
// return "" + y + m + d + h + n + s;
// }
/**
* 根据给定的格式,返回时间字符串。 和getFormatDate(String format)相似。
*
* @param format
* yyyy MM dd hh mm ss
* @return 返回一个时间字符串
*/
public static String getCurTimeByFormat(String format) {
Date newdate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(newdate);
}
/**
* 获取两个时间串时间的差值,单位为秒
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static long getDiff(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / 1000;
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return diff;
}
/**
* 获取小时/分钟/秒
*
* @param second
* 秒
* @return 包含小时、分钟、秒的时间字符串,例如3小时23分钟13秒。
*/
public static String getHour(long second) {
long hour = second / 60 / 60;
long minute = (second - hour * 60 * 60) / 60;
long sec = (second - hour * 60 * 60) - minute * 60;
return hour + "小时" + minute + "分钟" + sec + "秒";
}
/**
*
* 获取小时/分钟/秒/MS
*
*
*
* @param ms
*
* 秒
*
* @return 包含小时、分钟、秒的时间字符串,例如00h02m35s839ms。
*/
public static String getMsHour(long ms) {
long lms = ms % 1000;
long lm = ms / 1000;
long hour = lm / 60 / 60;
long minute = (lm - hour * 60 * 60) / 60;
long sec = (lm - hour * 60 * 60) - minute * 60;
String strHour = "h";
String strMinute = "m";
String strSec = "s";
String strLms = "ms";
if (hour < 10) {
strHour = "0" + hour + strHour;
} else {
strHour = hour + strHour;
}
if (minute < 10) {
strMinute = "0" + minute + strMinute;
} else {
strMinute = minute + strMinute;
}
if (sec < 10) {
strSec = "0" + sec + strSec;
} else {
strSec = sec + strSec;
}
if (lms < 10) {
strLms = "00" + lms + strLms;
} else if (lms < 100) {
strLms = "0" + lms + strLms;
} else {
strLms = lms + strLms;
}
String retVal = "0";
if (strHour.contains("00") == false) {
retVal += strHour;
}
if (strMinute.contains("00") == false) {
retVal += strMinute;
}
if (strSec.contains("00") == false) {
retVal += strSec;
}
if (strLms.contains("000") == false) {
retVal += strLms;
}
if ("0".equals(retVal)) {
retVal = "0ms";
} else {
retVal = CmnStrUtils.trimLeftChar(retVal,"0");
}
return retVal;
}
/**
* 返回指定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getDateTime(long microsecond)throws Throwable {
return getFormatDateTime(new Date(microsecond), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回指定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getDateTime(long microsecond, String pattarn)throws Throwable {
return getFormatDateTime(new Date(microsecond), pattarn);
}
/**
* 返回当前时间加实数小时后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return Float 加几实数小时.
*/
public static String getDateByAddFltHour(float flt)throws Throwable {
int addMinute = (int) (flt * 60);
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(GregorianCalendar.MINUTE, addMinute);
return getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回指定时间加指定小时数后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return 时间.
*/
public static String getDateByAddHour(String datetime, String pattarn, int minute)throws Throwable {
String returnTime = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat(pattarn);
Date date;
try {
date = ft.parse(datetime);
cal.setTime(date);
cal.add(GregorianCalendar.MINUTE, minute);
returnTime = getFormatDateTime(cal.getTime(), pattarn);
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return returnTime;
}
/**
* 获取两个时间串时间的差值,单位为小时
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static int getDiffHour(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / (1000 * 60 * 60);
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return new Long(diff).intValue();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @return 年份下拉框的html
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* 例如开始年份为2001结束年份为2005那么下拉框就有五个值。(2001、2002、2003、2004、2005)。
* @return 返回年份的下拉框的html。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank,
String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得天的下拉框
*/
public static String getDaySelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取天的下拉框
*/
public static String getDaySelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 计算两天之间有多少个周末(这个周末,指星期六和星期天,一个周末返回结果为2,两个为4,以此类推。) (此方法目前用于统计司机用车记录。)
* 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 开始日期 ,格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 结束日期 ,格式"yyyy/MM/dd"或者"yyyy-MM-dd"
* @return int
*/
public static int countWeekend(String startDate, String endDate) {
int result = 0;
Date sdate = null;
Date edate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
edate = getDateObj(endDate, "/");// 结束日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
edate = getDateObj(endDate, "-");// 结束日期
}
// 首先计算出都有那些日期,然后找出星期六星期天的日期
int sumDays = Math.abs(getDiffDays(startDate, endDate));
int dayOfWeek = 0;
for (int i = 0; i <= sumDays; i++) {
dayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 计算每过一天的日期
if (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六
result++;
}
}
return result;
}
/**
* 计算两个日期之间相差的天数
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int daysBetween(Date smdate,Date bdate) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
smdate=sdf.parse(sdf.format(smdate));
bdate=sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
*字符串的日期格式的计算
*/
public static int daysBetween(String smdate,String bdate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 返回两个日期之间相差多少天。 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @return 整数。
*/
public static int getDiffDays(String startDate, String endDate) {
long diff = 0;
SimpleDateFormat ft = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
ft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
Date sDate = ft.parse(startDate + " 00:00:00");
Date eDate = ft.parse(endDate + " 00:00:00");
diff = eDate.getTime() - sDate.getTime();
diff = diff / 86400000;// 1000*60*60*24;
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return (int) diff;
}
/**
* 返回两个日期之间的详细日期数组(包括开始日期和结束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回数组
* {"2007/07/01","2007/07/02","2007/07/03"} 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @param endDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @return 返回一个字符串数组对象
*/
public static String[] getArrayDiffDays(String startDate, String endDate)throws Throwable {
int LEN = 0; // 用来计算两天之间总共有多少天
// 如果结束日期和开始日期相同
if (startDate.equals(endDate)) {
return new String[] { startDate };
}
Date sdate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
}
LEN = getDiffDays(startDate, endDate);
String[] dateResult = new String[LEN + 1];
dateResult[0] = startDate;
for (int i = 1; i < LEN + 1; i++) {
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i), "yyyy/MM/dd");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i), "yyyy-MM-dd");
}
}
return dateResult;
}
/**
* 判断一个日期是否在开始日期和结束日期之间。
*
* @param srcDate
* 目标日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param startDate
* 开始日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param endDate
* 结束日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 大于等于开始日期小于等于结束日期,那么返回true,否则返回false
*/
public static boolean isInStartEnd(String srcDate, String startDate, String endDate) {
if (startDate.compareTo(srcDate) <= 0 && endDate.compareTo(srcDate) >= 0) {
return true;
} else {
return false;
}
}
/**
* 获取天的下拉框,默认的为1-4。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取季度的下拉框,默认的为1-4
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDate(String argDate) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + "/01/01";
}
if (LEN == 2) {
result = str[0] + "/" + str[1] + "/01";
}
if (LEN == 3) {
result = str[0] + "/" + str[1] + "/" + str[2];
}
return result;
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDateWithSplit(String argDate, String split) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
if (split == null || split.trim().equals("")) {
split = "-";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
// 如果是格式为yyyy-MM-dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("-") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + split + "01" + split + "01";
}
if (LEN == 2) {
result = str[0] + split + str[1] + split + "01";
}
if (LEN == 3) {
result = str[0] + split + str[1] + split + str[2];
}
return result;
}
/**
* 返回指定日期的的下一个月的天数。
*
* @param argDate
* 格式为yyyy-MM-dd或者yyyy/MM/dd
* @return 下一个月的天数。
*/
public static int getNextMonthDays(String argDate) {
String[] temp = null;
if (argDate.indexOf("/") > 0) {
temp = argDate.split("/");
}
if (argDate.indexOf("-") > 0) {
temp = argDate.split("-");
}
Calendar cal = new GregorianCalendar(new Integer(temp[0]).intValue(), new Integer(temp[1]).intValue() - 1,
new Integer(temp[2]).intValue());
int curMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.MONTH, curMonth + 1);
int curyear = cal.get(Calendar.YEAR);// 当前年份
curMonth = cal.get(Calendar.MONTH);// 当前月份,0-11
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth];
}
public static String getDateStr(String str) {
str=str.replace("/", "");
//System.out.println(str);
str=str.replace("\\", "");
//System.out.println(str);
str=str.replace("-", "");
//System.out.println(str);
str=str.replace(" ", "");
//System.out.println(str);
str=str.replace(":", "");
//System.out.println(str);
return str;
}
public static boolean isDateNumber(String str) {
boolean isDateNumber = false;
String s = getDateStr(str);
int len = str.length();
if (len == {
} else if (len ==14) {
}
return isDateNumber;
}
public static String convJtGDate(String src) throws ParseException {
Integer gc = 0;
String gg = src.substring(0, 2);
Integer yy = Integer.parseInt(src.substring(2, src.indexOf("年")));
Integer mm = Integer.parseInt(src.substring(src.indexOf("年") + 1,
src.indexOf("月")));
Integer dd = Integer.parseInt(src.substring(src.indexOf("月") + 1,
src.indexOf("日")));
if (gg.equals("平成")) {
gc = 4;
} else if (gg.equals("昭和")) {
gc = 3;
} else if (gg.equals("大正")) {
gc = 2;
} else if (gg.equals("明治")) {
gc = 1;
}
Locale.setDefault(new Locale("ja", "JP", "JP"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.ERA, gc);
cal.set(yy, mm - 1, dd);
Locale.setDefault(new Locale("en", "EN", "EN"));
SimpleDateFormat gdf = new SimpleDateFormat("yyyy/MM/dd");
return gdf.format(cal.getTime());
}
public static String convGtJDate(String src) throws ParseException {
Locale.setDefault(new Locale("en", "EN", "EN"));
SimpleDateFormat gdf = new SimpleDateFormat("yyyyMMdd");
Locale.setDefault(new Locale("ja", "JP", "JP"));
SimpleDateFormat jdf = new SimpleDateFormat("GGGGyy年MM月dd日");
return jdf.format(gdf.parse(src.replace("/", "")));
}
}
-------C:\aa\common\CmnFileUtils.java
/**
* Copyright (c) 2012, Java CNC/CSJ for tools. All rights reserved.
*/
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import jp.co.csj.tools.utils.common.CsjPath;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.file.core.CsjSameFilesInfo;
import jp.co.csj.tools.utils.key.CsjDesEncrypt;
import jp.co.csj.tools.utils.msg.dbtools.CsjDbToolsMsg;
import jp.co.csj.tools.utils.reg.RegConstStr;
/**
* CsjDirectory
* @author cuishuangjia@163.com
* @version 1.0
* @since 1.6
*/
public class CmnFileUtils {
public static void main(String[] args) {
try {
CmnLog5j.initLog5j("log.txt", IConstFile.ENCODE_UTF_8);
List<File> fileLst = getFilesList("C:\\aa", true);
for (File f: fileLst) {
try {
List<String> strlst = getFileContent(f, IConstFile.ENCODE_UTF_8);
for(String s : strlst) {
CmnLog5j.writeLine(s);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
CmnLog5j.closeLog5j();
}
}
public static LinkedList<File> getFilesListWithOutStr(String filePath,
boolean isHaveSubFile, String startStr, String endStr) {
LinkedList<File> tList = getFilesList(filePath, isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isNotEmpty(startStr) && fNm.startsWith(startStr)) {
continue;
} else if (CmnStrUtils.isNotEmpty(endStr) && fNm.endsWith(endStr)) {
continue;
}
}
return retList;
}
public static boolean isFiles(String text, String splitStr) {
boolean retVal = true;
String[] strArr = text.split(splitStr);
for (String str : strArr) {
if (CmnStrUtils.isEmpty(str)) {
continue;
}
File f = new File(str);
if (f.isFile() == false) {
retVal = false;
break;
}
}
return retVal;
}
/**
* * @param
*/
public static int checkFilePath(String filePath) {
int retVal = IConstFile.IS_ERROR;
File f = new File(filePath);
if (f.isDirectory()) {
retVal = IConstFile.IS_PATH;
} else if (f.isFile()) {
retVal = IConstFile.IS_FILE;
} else if (filePath.contains(";") && isFiles(filePath, ";")) {
retVal = IConstFile.IS_FILES;
}
return retVal;
}
public static LinkedList<File> getExcelFileByAbsPath(String filePath,boolean isHaveSubFile) {
LinkedList<File> retList = new LinkedList<File>();
int retVal = checkFilePath(filePath);
if (retVal == IConstFile.IS_PATH) {
retList= getFilesListReg(filePath, isHaveSubFile,RegConstStr.EXCEL_REG_DOT);
} else if (retVal == IConstFile.IS_FILE) {
retList.add(new File(filePath));
} else if (retVal == IConstFile.IS_FILES) {
String[] strArr = filePath.split(",");
for (String str : strArr) {
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(new File(str));
}
}
}
return retList;
}
public static LinkedList<File> getFilesListWithStr(String filePath,
boolean isHaveSubFile,String startStr,String endStr) {
LinkedList<File> tList =getFilesList(filePath,isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isNotEmpty(startStr)&& fNm.startsWith(startStr)) {
retList.add(f);
} else if (CmnStrUtils.isNotEmpty(endStr)&& fNm.endsWith(endStr)) {
retList.add(f);
}
}
return retList;
}
public static TreeMap<Long,File> getFilesModifyTimeMapReg(String filePath,
boolean isHaveSubFile,String regex) {
LinkedList<File> tList =getFilesList(filePath,isHaveSubFile);
TreeMap<Long,File> retMap = new TreeMap<Long, File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isEmpty(regex)||fNm.matches(regex)) {
retMap.put(f.lastModified(), f);
}
}
return retMap;
}
public static LinkedList<File> getFilesListReg(String filePath,
boolean isHaveSubFile,String regex) {
LinkedList<File> fList = getFilesList(filePath,isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : fList) {
if (CmnStrUtils.isEmpty(regex)||f.getName().matches(regex)) {
retList.add(f);
}
}
return retList;
}
/**
* @param String filePath
* @param boolean isHaveSubFile
* @return
*/
public static LinkedList<File> getFilesList(String filePath,
boolean isHaveSubFile) {
LinkedList<File> retList = new LinkedList<File>();
LinkedList<File> list = new LinkedList<File>();
File dir = new File(filePath);
File file[] = dir.listFiles();
if (null == file) {
return retList;
}
for (int i = 0; i < file.length; i++) {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
if (file[i].isDirectory())
list.add(file[i]);
else
retList.add(file[i]);
}
if (isHaveSubFile) {
File tmp;
while (!list.isEmpty()) {
tmp = list.removeFirst();
if (tmp.isDirectory()) {
file = tmp.listFiles();
if (file == null)
continue;
for (int i = 0; i < file.length; i++) {
if (file[i].isDirectory())
list.add(file[i]);
else {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
retList.add(file[i]);
}
}
} else {
// if (tmp.getName().endsWith(".scc")) {
// continue;
// }
retList.add(tmp);
}
}
}
return retList;
}
public static boolean reNameFile(File f, String newNm) {
File mm = new File(f.getParent() + CsjProcess.s_f_s + newNm);
return f.renameTo(mm);
}
// /**
// *
// * @param filePathList
// * @return
// */
// public static LinkedList<File> getFilesList(List<String> filePathList, boolean isHaveSubFile) {
// LinkedList<File> retList = new LinkedList<File>();
// for (String filePath : filePathList) {
// LinkedList<File> fileList = getFilesList(filePath, isHaveSubFile);
// for (File file : fileList) {
// retList.add(file);
// }
// }
// return retList;
// }
//
// /**
// *
// * @param filePath
// * @return
// */
// public static LinkedList<File> getFilesList(String filePath,
// boolean isHaveSubFile) {
//
// LinkedList<File> retList = new LinkedList<File>();
// LinkedList<File> list = new LinkedList<File>();
// File dir = new File(filePath);
// File file[] = dir.listFiles();
// if (null == file) {
// System.out.println("a");
// }
//
// for (int i = 0; i < file.length; i++) {
//
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
//
// if (file[i].isDirectory())
// list.add(file[i]);
// else
// retList.add(file[i]);
// }
//
// if (isHaveSubFile) {
// File tmp;
// while (!list.isEmpty()) {
// tmp = list.removeFirst();
//
// if (tmp.isDirectory()) {
// file = tmp.listFiles();
// if (file == null)
// continue;
// for (int i = 0; i < file.length; i++) {
// if (file[i].isDirectory())
// list.add(file[i]);
// else {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
// retList.add(file[i]);
// }
// }
// } else {
// if (tmp.getName().endsWith(".scc")) {
// continue;
// }
// retList.add(tmp);
// }
// }
// }
//
// return retList;
// }
public static LinkedHashMap<String, File> getFilesMap(String filePath, boolean isHaveSubFile) {
LinkedHashMap<String, File> retMap = new LinkedHashMap<String, File>();
List<File> fileList = getFilesList(filePath, isHaveSubFile);
for (File f : fileList) {
retMap.put(f.getName(), f);
}
return retMap;
}
public static Map<String, File> getFilesTreeMap(String filePath, boolean isHaveSubFile) {
Map<String, File> retMap = new TreeMap<String, File>();
List<File> fileList = getFilesList(filePath, isHaveSubFile);
for (File f : fileList) {
retMap.put(f.getName(), f);
}
return retMap;
}
public static long getFileSizes(File f) {// 取得文件大小
long s = 0;
FileInputStream fis = null;
try {
if (f.exists()) {
fis = new FileInputStream(f);
s = fis.available();
} else {
f.createNewFile();
System.out.println("file not exist!");
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
CmnLog.logger.info(e.getMessage());
}
}
return s;
}
public static String formatFileSize(long fileS) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
public static String getFileSize(File f) {
return formatFileSize(getFileSizes(f));
}
public static long getFileMaxLine(File f) {
long retVal = 0;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f), IConstFile.ENCODE_SHIFT_JIS));
while (reader.ready()) {
reader.readLine();
retVal++;
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retVal;
}
public static void removeFiles(String filePath) throws Throwable {
try {
File f = new File(filePath);
if (f!=null) {
delFile(f);
}
} catch (Throwable e) {
throw e;
}
}
public static void delFile(String path,String fileNmReg,boolean haveSub) throws Throwable {
try {
File f = new File(path);
if (CmnStrUtils.isEmpty(fileNmReg)) {
delFile(f);
}else if (f.isDirectory()) {
List<File> fLst = getFilesList(f.getAbsolutePath(), haveSub);
for (File ft : fLst) {
if (CmnStrUtils.isEmpty(fileNmReg)) {
ft.delete();
}else if (ft.getName().matches(fileNmReg)) {
ft.delete();
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static void delFile(File f)throws Throwable {
try {
if (f == null) {
return;
}
if (f.isDirectory()) {
File[] list = f.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
delFile(list[i]);
}else{
if(list[i].isFile())
list[i].delete();
}
}
f.delete();
} else {
if (f.isFile())
f.delete();
}
} catch (Throwable e) {
throw e;
}
}
/**
* @param text
* @param string
* @throws Throwable
*/
public static void copyDbtoolsInfo(String newIniNm, String iniText) throws Throwable {
if (CmnStrUtils.isNotEmpty(iniText)) {
copyFile(CsjPath.s_file_db_info_path, iniText + ".xml", CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
} else {
LinkedList<File> fileList = CmnFileUtils.getFilesListWithStr(CsjPath.s_file_db_info_path, false, "", IConstFile.DOT_INI);
if (fileList.size()!=0) {
File f = fileList.get(0);
copyFile(CsjPath.s_file_db_info_path, f.getName(), CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
} else {
fileList = CmnFileUtils.getFilesListWithStr(CsjPath.s_file_db_info_path, false, "", IConstFile.DOT_INI_BAK);
File f = fileList.get(0);
copyFile(CsjPath.s_file_db_info_path, f.getName(), CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
}
}
}
private static String formatToFolder(String folder) {
if (folder.endsWith(CsjProcess.s_f_s)) {
return folder;
} else {
return folder + CsjProcess.s_f_s;
}
}
/**
* @param fromFolder
* @param fromFile
* @param toFolder
* @param toFile
* @throws Throwable
*/
public static void copyFile(String fromFolder, String fromFile,
String toFolder, String toFile,boolean toFolderAutoCreate) throws Throwable {
try {
if (toFolderAutoCreate) {
File makeFolder = new File(toFolder);
makeFolder.mkdirs();
}
boolean isHaveSubFile = false;
if (fromFolder.toLowerCase().startsWith("havesub:")) {
isHaveSubFile = true;
}
fromFolder = CmnStrUtils.fromAtoBByTrim(fromFolder,"havesub:", "");
boolean isReg = false;
if (fromFile.startsWith("reg:")) {
isReg = true;
}
fromFile = CmnStrUtils.fromAtoBByTrim(fromFile,"reg:", "");
String fromStr = formatToFolder(fromFolder)+fromFile;
if (isReg) {
fromStr = formatToFolder(fromFolder);
}
String toStr = formatToFolder(toFolder)+toFile;
File from = new File(fromStr);
File to = new File(toStr);
if (from.isDirectory()) {
if (to.isDirectory()) {
if (isReg) {
LinkedList<File> fileLst = getFilesListReg(fromFolder, isHaveSubFile,fromFile);
for (File f : fileLst) {
String toPath = toStr+CmnStrUtils.fromAtoBByTrim(f.getParent()+CsjProcess.s_f_s, fromStr, "");
new File(toPath).mkdirs();
String batStr = "xcopy " + f.getAbsolutePath() + " " + toPath + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
}
} else {
LinkedList<File> fileLst = getFilesList(fromFolder, isHaveSubFile);
for (File f : fileLst) {
String toPath = toStr+CmnStrUtils.fromAtoBByTrim(f.getParent()+CsjProcess.s_f_s, fromStr, "");
new File(toPath).mkdirs();
String batStr = "xcopy " + f.getAbsolutePath() + " " + toPath + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
}
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000111) + CmnLog5j.addlrBracketsM(toStr, false));
}
} else if (from.isFile()) {
if (to.isDirectory()) {
String batStr = "xcopy " + from.getAbsolutePath() + " " + to + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
} else {
File tmpToFolder = new File(toFolder);
if (tmpToFolder.isDirectory()) {
String batStr = "xcopy " + from.getAbsolutePath() + " " + toFolder + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
File f = new File(toFolder+toFile);
if (f.isFile()) {
f.delete();
}
File fr = new File(toFolder+fromFile);
if (fr.isFile()) {
fr.renameTo(f);
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000113) + CmnLog5j.addlrBracketsM(toFolder, false));
}
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000112) + CmnLog5j.addlrBracketsM(fromStr, false));
}
} catch (Throwable e) {
throw e;
}
}
////////////////////////////
public static void writeWithbBlank(BufferedWriter writer, String str,
int blankCount) {
if (writer == null) {
return;
}
try {
writer.write(getBlank(str, blankCount, true));
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
}
public static String getTxtFileInfo(String fileNm, String encode,
String splitLine) throws Throwable {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(fileNm), encode));
while (reader.ready()) {
buffer.append(reader.readLine() + splitLine);
}
return buffer.toString();
}
public static String getBlank(String str, int blankCount, boolean isBefore) {
String strBlank = CsjConst.EMPTY;
for (int i = 0; i < blankCount; i++) {
strBlank += CsjConst.SIGN_SPACE_4;
}
if (isBefore) {
return strBlank + str;
} else {
return str + strBlank;
}
}
/**
* @param writer
* @param copyRightList
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer,
List<String> strList, int blankCount) {
for (String str : strList) {
writeWithbBlank(writer, str, blankCount);
}
}
/**
* @param writer
* @param copyRightList
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer, String paraStr,
List<String> strList, int blankCount,
boolean isLeft) {
for (String str : strList) {
if (isLeft) {
writeWithbBlank(writer, paraStr + str, blankCount);
} else {
writeWithbBlank(writer, str + paraStr, blankCount);
}
}
}
/**
* @param writer
* @param importMap
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer, String paraStr,
Map<String, String> map, int blankCount,
boolean isLeft) {
for (Entry<String, String> entry : map.entrySet()) {
if (isLeft) {
writeWithbBlank(writer, paraStr + entry.getKey(), blankCount);
} else {
writeWithbBlank(writer, entry.getKey() + paraStr, blankCount);
}
}
}
/**
* @param writer
* @param importMap
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer,
Map<String, String> map, int blankCount) {
for (Entry<String, String> entry : map.entrySet()) {
writeWithbBlank(writer, entry.getKey(), blankCount);
}
}
public static LinkedHashMap<String, String> getFileMap(String filePath,
String encode, boolean isKeyLineNo) {
LinkedHashMap<String, String> retMap = new LinkedHashMap<String, String>();
long retVal = 0;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
while (reader.ready()) {
if (isKeyLineNo) {
retMap.put(String.valueOf(retVal++), reader.readLine());
} else {
retMap.put(reader.readLine(), String.valueOf(retVal++));
}
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
}
return retMap;
}
public static LinkedHashMap<String, List<String>> getKeyFileMap(
String filePath, String encode) {
LinkedHashMap<String, List<String>> retMap = new LinkedHashMap<String, List<String>>();
CmnLog.logger.info(new File(filePath).getAbsolutePath());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
while (reader.ready()) {
String line = reader.readLine();
CmnLog.logger.info(line);
if (CmnStrUtils.isNotEmpty(line)) {
String strLine = CsjDesEncrypt.uncode(line);
strLine = CmnLanIPUtils.unLongStrKey(strLine);
String str[] = strLine.split(CsjConst.SIGN_AT);
if (str.length == 4) {
// CsjLog4j.info(CsjDesEncrypt.uncode(line).toString());
List<String> list = new ArrayList<String>();
list.add(str[1]);
list.add(str[2]);
retMap.put(str[0], list);
}
}
// if (line != null && line.length() == 80) {
// String key = line.substring(0, 48);
// System.out.println(CsjDesEncrypt.uncode(key));
// String pay = line.substring(48, 64);
// System.out.println(CsjDesEncrypt.uncode(key));
// String date = line.substring(64,96);
// System.out.println(CsjDesEncrypt.uncode(key));
// retMap.put(key,pay+"|||"+date);
// }
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
}
return retMap;
}
public static void writeFile(String logPath, String fileNm, String enCode,
List<String> strList) throws Throwable {
File file = new File(logPath);
file.mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logPath + fileNm), enCode));
for (String str : strList) {
writeWithbBlank(writer, str, 0);
}
writer.close();
}
public static boolean isFileExist(String filePath) {
return new File(filePath).isFile();
}
public static boolean isFolderExist(String folderPath) {
return new File(folderPath).isDirectory();
}
public static void reWriteFile(String filePath, String enCode,
Map<String,String> regexMap,String cr) throws Throwable {
List<String> strLst = getFileContent(filePath, enCode);
List<String> strLstTmp = new ArrayList<String>();
for (String s:strLst) {
for (String key : regexMap.keySet()) {
if (s.matches(key)) {
s = regexMap.get(key);
break;
}
}
strLstTmp.add(s);
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), enCode));
for (String str : strLstTmp) {
writer.write(str);
writer.write(cr);
}
writer.close();
}
public static String getFileNm(String filePath) {
String retVal = CsjConst.EMPTY;
File file = new File(filePath);
retVal = file.getName();
return retVal;
}
public static boolean
isTwoFileNmSame(String fileOldPath, String filNewPath) {
return getFileNm(fileOldPath).equals(getFileNm(filNewPath));
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
*/
public static List<CsjSameFilesInfo> getSameFile(
LinkedHashMap<String, File> oldFilesMap,
LinkedHashMap<String, File> newFilesMap) {
List<CsjSameFilesInfo> retList = new ArrayList<CsjSameFilesInfo>();
for (Entry<String, File> entry : newFilesMap.entrySet()) {
String key = entry.getKey();
if (oldFilesMap.containsKey(key)) {
CsjSameFilesInfo csjSameFilesInfo = new CsjSameFilesInfo();
csjSameFilesInfo.setFileNm(key);
csjSameFilesInfo.getFilePaths().add(
oldFilesMap.get(key).getAbsolutePath());
csjSameFilesInfo.getFilePaths().add(
newFilesMap.get(key).getAbsolutePath());
retList.add(csjSameFilesInfo);
}
}
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFileContent(File f, String encode)
throws Throwable {
List<String> retList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f),
encode));
while (reader.ready()) {
retList.add(reader.readLine());
}
reader.close();
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFileContent(String path, String encode)
throws Throwable {
List<String> retList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(path)),
encode));
while (reader.ready()) {
retList.add(reader.readLine());
}
reader.close();
return retList;
}
public static Map<Integer,String> getFileContents(String filePath,String splitCh,int col,int rowStart,int rowEnd,String encode) throws Throwable {
Map<Integer,String> retMap = new HashMap<Integer, String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
int i = 0;
while (reader.ready()) {
String line = reader.readLine();
if (i >= rowStart && i <= rowEnd) {
String[] sa = line.split(splitCh);
if (col < sa.length ) {
retMap.put(i-rowStart, sa[col]);
}
}
i++;
}
reader.close();
return retMap;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFilesContent(String path, String encode)
throws Throwable {
List<File> fileList = CmnFileUtils.getFilesList(path, false);
List<String> retList = new ArrayList<String>();
for (File f : fileList) {
List<String> strList = getFileContent(f, encode);
for (String str : strList) {
retList.add(str);
}
}
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void copyFile(String path, String nm, String newPath,
String newNm, String encode) throws Throwable {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(path + nm),
encode));
File file = new File(newPath);
file.mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(newPath + newNm), encode));
while (reader.ready()) {
writeWithbBlank(writer, reader.readLine(), 0);
}
writer.close();
reader.close();
}
/**
* @param fileMap
* @param string
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void createFile(TreeMap<Long, File> fileMap, String outputFileName, String encode) throws Throwable {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), encode));
for (File f : fileMap.values()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f.getAbsolutePath()),encode));
while (reader.ready()) {
String line = reader.readLine();
CmnLog5j.writeLine(writer, line);
}
reader.close();
}
CmnLog5j.close(writer);
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnLanIPUtils.java
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import jp.co.csj.tools.utils.common.CsjCheck;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.key.CsjDesEncrypt;
import jp.co.csj.tools.utils.reg.RegConstStr;
import jp.co.csj.utils.exe.net.CsjMacAddress;
/**
* 使用java线程扫描局域网ip简单方案
*
* @author Administrator
*
*/
public class CmnLanIPUtils {
public static long step = 0;
public static String proty = CsjProcess.s_pj_path + "properties"
+ CsjProcess.s_f_s;
public static String keyNm = "key.dll";
public static String keyTNm = "keyT.dll";
public static String s_file_key_T_file = "properties" + CsjProcess.s_f_s
+ keyTNm;
public static String s_file_key_file = "properties" + CsjProcess.s_f_s
+ "key.dll";
public static boolean isAccessNet=false;
/**
* @throws Throwable
*/
public static void writeLimitDate() throws Throwable {
List<String> strList = new ArrayList<String>();
strList.add(CsjDesEncrypt.encode(enLongStrKey(CsjCheck.limitDate, 10)));
String folder = CsjProcess.s_pj_path + "properties"
+ CsjProcess.s_f_s;
System.out.println(folder);
CmnFileUtils.writeFile(folder, keyTNm, IConstFile.ENCODE_UTF_8,
strList);
}
/**
* @throws Throwable
*/
public static void writeLocalMacKey(String key) throws Throwable {
List<String> strList = new ArrayList<String>();
strList.add(key);
CmnFileUtils
.writeFile(proty, keyNm, IConstFile.ENCODE_UTF_8, strList);
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String getOneKey(boolean isPayMoney, String strMac,
String strDate) throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String stepStr = CmnRandomUtils.createRadomStrs(6, true, false);
String strPre = "unpay";
if (isPayMoney) {
strPre = "payed";
}
strMac = strMac.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
String str = strMac + CsjConst.SIGN_AT + strMac1 + strPre
+ CsjConst.SIGN_AT + strMac2 + strDate + CsjConst.SIGN_AT
+ stepStr;
System.out.println(strMac);
System.out.println(strPre);
System.out.println(strDate);
System.out.println(stepStr);
System.out.println(str);
str = enLongStrKey(str,10);
str = CsjDesEncrypt.encode(str);
System.out.println(str);
return str;
}
/**
* @param str
* @param level
* @return
*/
public static String enLongStrKey(String str, int level) {
for (int i = 0; i < CsjConst.SIGN_RANDOM.length; i++) {
for (int index = 0; index < level; index++) {
int num = CmnRandomUtils.createRadomNum(CsjConst.SIGN_RANDOM.length, true);
str = CmnStrUtils.insertChar(str,CsjConst.SIGN_RANDOM[num],CmnRandomUtils.createRadomNum(str.length(), true)%str.length());
}
}
return str;
}
/**
* @param strLine
* @return
*/
public static String unLongStrKey(String strLine) {
for (int i = 0; i < CsjConst.SIGN_RANDOM.length; i++) {
strLine=CmnStrUtils.funReplace(strLine, CsjConst.SIGN_RANDOM[i], "");
}
return strLine;
}
public static void main(String[] args) {
String strMac = "00-26-C7-72-DC-D4";
strMac = strMac.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
System.out.println(strMac1);
System.out.println(strMac2);
System.out.println("abcdefghi".substring(3));
// if ("192.168.20.123s".matches(RegConstStr.IP)) {
// System.out.println("ok");
// }
try {
writeLimitDate();
// writeLocalMacKey(getOneKey());
System.out.println("REGEDIT SUCCESS");
// writeLanMacKey("c:\\", "key.dll",CsjFileConst.ENCODE_UTF_8);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
System.out.println("REGEDIT ERROR");
}
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String getOneKeyUncode(boolean isPayMoney) throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String code = CsjDesEncrypt.encode(CsjProcess.s_local_inet_addr_with_line);
String limitDate = getKeyTValLine0();
String strDate = limitDate;
String strPre = "unpay";
if (isPayMoney) {
strPre = "payed";
}
String strMac = CsjProcess.s_local_inet_addr_with_line.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
String str = CsjDesEncrypt.encode(strMac + CsjConst.SIGN_AT + strMac1
+ strPre + CsjConst.SIGN_AT + strMac2 + strDate
+ CsjConst.SIGN_AT + CmnRandomUtils.createRadomStrs(6, true, false));
return str;
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String regeditKey(String mac, String strDate)
throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String str = mac + "payed" + strDate + 000000;
str = CsjDesEncrypt.encode(str);
return str;
}
public static String getKeyTValLine0() throws Throwable {
String key = CmnFileUtils.getFileContent(
new File(s_file_key_T_file), IConstFile.ENCODE_UTF_8).get(0);
String unkey = CsjDesEncrypt.uncode(key);
return unLongStrKey(unkey);
}
public static void isAccessNet() throws Throwable {
if (isAccessNet) {
List<String> lst = CmnFileUtils.getFileContent(
new File(s_file_key_T_file), IConstFile.ENCODE_UTF_8);
if (lst.size()>1) {
isAccessNet = !lst.get(1).equals("NN");
}
}
}
public static String getKeyDateVal() throws Throwable {
return CsjDesEncrypt.uncode(CmnFileUtils.getFileContent(
new File(s_file_key_file), IConstFile.ENCODE_UTF_8).get(0));
}
/**
* @throws Throwable
*
*/
public static void writeLanMacKey() throws Throwable {
System.out.println("begin......");
CmnLanIPUtils ip = new CmnLanIPUtils();
List<String> list = ip.getLanIPArrayList();
List<String> macList = ip.getLanIPArrayList();
System.out.println("---------------- list ----------------");
Thread.sleep(5000);
for (String str : list) {
String mac = CsjMacAddress.run(str);
if (CmnStrUtils.isNotEmpty(mac) && mac.matches(RegConstStr.MAC)) {
String stepStr = CmnStrUtils.leftFillChar(
String.valueOf(step++), '0', 6);
String strDate = CsjCheck.limitDate + stepStr;
macList.add(CsjDesEncrypt.encode(mac)
+ CsjDesEncrypt.encode(strDate));
}
}
CmnFileUtils
.writeFile(proty, keyNm, IConstFile.ENCODE_UTF_8, macList);
System.out.println("最后有多少个===>" + list.size());
}
public ArrayList<String> getLanIPArrayList() {
ArrayList<String> arrayIP = null;
try {
InitSystem initSystem = null;
initSystem = new InitSystem();
Thread thread = new Thread(initSystem);
thread.start();
thread.join();
arrayIP = initSystem.getArrayIPUsed();
} catch (UnknownHostException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return arrayIP;
}
private class InitSystem implements Runnable {
private int firstIP = 2;// 查询的 IP 地址的最后一位起始点
private int lastIP = 255;// 查询的 IP 地址的最后一位结束点
private volatile ArrayList<Thread> arrayThread;// 子线程段
private final int MAXTHREADNUM = 30; // 最大同时进行的子线程数量
private int threadNumNow;// 当前正在进行的子线程数量
private volatile ArrayList<String> arrayIP;// 局域网查询所有可能的 IP 地址的结果集
private volatile ArrayList<String> arrayIPUsed;// 局域网查询已经使用的 IP 地址的结果集
private InitSystem(String ip) {
System.out.println("IP===>" + ip);
arrayIP = new ArrayList<String>();
arrayIPUsed = new ArrayList<String>();
arrayThread = new ArrayList<Thread>();
setIPAddressList(ip);
}
private InitSystem() throws UnknownHostException {
this(InetAddress.getLocalHost().getHostAddress());
}
private synchronized ArrayList<String> getArrayIPUsed() {
try {
System.out.println("getArrayIPUsed: arrayIP.size===>"
+ arrayIP.size());
while (arrayIP.size() > 0) {
Thread.sleep(300);
}
} catch (InterruptedException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return arrayIPUsed;
}
private void setIPAddressList(String ip) {
// 根据这个 ip 地址查询它所在的局域网的所有可能 IP 地址的集合
int lastPointIndex = ip.lastIndexOf('.');
String stringIPHead = ip.substring(0, ++lastPointIndex);
System.out.println("stringIPHead===>" + stringIPHead);
String stringIP = null;
for (int i = firstIP; i <= lastIP; i++) {
stringIP = stringIPHead + i;
arrayIP.add(stringIP);
}
System.out.println("进放到这里...arrayIP的总个数:" + arrayIP.size());
}
public void run() {
synchronized (this) {
try {
System.out.println("run() arrayIP.size()===>"
+ arrayIP.size());
System.out
.println("run() threadNumNow===>" + threadNumNow);
System.out.println("arrayThread.size()"
+ arrayThread.size());
while (arrayIP.size() > 0) {
while (threadNumNow >= MAXTHREADNUM) {
System.out.println("线程超出30,中止后面的...");
for (Thread thread : arrayThread) {
if (!thread.getState().equals(
Thread.State.TERMINATED)) {
thread.join(5);
}
--threadNumNow;
}
arrayThread = new ArrayList<Thread>();
}
Thread thread = new Thread(new InnerClass(arrayIP
.remove(0)));
thread.start();
threadNumNow++;
arrayThread.add(thread);
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
}
}
private class InnerClass implements Runnable {
// 线程查询一个 IP 是否是可以连接的 是则加入到相应的 IP 数组
private String ip;
private InnerClass(String ip) {
System.out.println("InnerClass ip===>" + ip);
this.ip = ip;
}
private boolean isUsedIPAddress(String ip) {
System.out.println("isUsedIPAddress===>" + ip);
synchronized (this) {
System.out.println("进入此地.....");
// 判断这个 IP 地址在当前局域网中是否是可连接的 IP
Process process = null;
BufferedReader bufReader = null;
String bufReadLineString = null;
try {
process = Runtime.getRuntime().exec(
"ping " + ip + " -w 100 -n 1");
bufReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
for (int i = 0; i < 6 && bufReader != null; i++) {
bufReader.readLine();
}
bufReadLineString = bufReader.readLine();
System.out.println("bufReadLineString===>"
+ bufReadLineString);
if (bufReadLineString == null) {
process.destroy();
return false;
}
if (bufReadLineString.indexOf("timed out") > 0
|| bufReadLineString.length() < 17
|| bufReadLineString.indexOf("invalid") > 0) {
process.destroy();
return false;
}
} catch (IOException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
process.destroy();
return true;
}
}
public void run() {
synchronized (this) {
if (isUsedIPAddress(ip)) {
arrayIPUsed.add(ip);
}
}
}
}
}
}
//
// 利用IP地址获得局域网计算机的名字、mac地址、工作组
//
// System.out.println("192.168.1.187对应网卡的MAC是:");
//
// NetworkInterface
// ne=NetworkInterface.getByInetAddress(InetAddress.getByName("192.168.1.187"));
//
// byte[]mac=ne.getHardwareAddress();
//
// String mac_s=hexByte(mac[0])+":"+hexByte(mac[1])+":"+
// hexByte(mac[2])+":"+hexByte(mac[3])+":"+
// hexByte(mac[4])+":"+hexByte(mac[5]);System.out.println(mac_s);
//
// 程序运行结果: 192.168.1.187对应网卡的MAC是: 00:0c:f1:20:75:58
-------C:\aa\common\CmnLog.java
package org.mydbsee.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class CmnLog {
public static Logger logger = LogManager.getLogger(CmnLog.class.getName());
public static void main(String[] args) {
logger.debug("aaaaaaaaaaa");
}
}
-------C:\aa\common\CmnLog5j.java
/**
*
*/
package org.mydbsee.common;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.log.constant.CsjLogConst;
/**
* @author Think
*
*/
public class CmnLog5j {
public static BufferedWriter s_log5j = null;
public static void main(String[] args) {
try {
initLog5j("c:\\1\\","a.txt",IConstFile.ENCODE_UTF_8);
s_log5j.write("1111");
s_log5j.write("\r\n");
s_log5j.write("2222");
closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void initLog5j(String logPath,String fileNm, String enCode) throws Throwable {
File file = new File(logPath);
file.mkdirs();
s_log5j = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logPath + fileNm), enCode));
}
public static void initLog5j(String filePath, String enCode) throws Throwable {
File file = new File(filePath);
s_log5j = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), enCode));
}
public static void closeLog5j() {
try {
if (s_log5j != null) {
s_log5j.close();
s_log5j=null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeLine(String str) {
CmnFileUtils.writeWithbBlank(s_log5j, str, 0);
}
public static void writeWithConsole(String str) {
CmnFileUtils.writeWithbBlank(s_log5j, str, 0);
System.out.println(str);
}
public static String getXlsPosLog(String filePath, String sheetNm, String row,String col, String content) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(filePath)) {
sb.append(CsjLogConst.SIGN_FILE_PATH + addlrBracketsM(filePath,true) );
}
if (CmnStrUtils.isNotEmpty(sheetNm)) {
sb.append(CsjLogConst.SIGN_SHEET_NM + addlrBracketsM(sheetNm,true) );
}
if (CmnStrUtils.isNotEmpty(row)) {
sb.append(CsjLogConst.SIGN_ROW + addlrBracketsM(row,true) );
}
if (CmnStrUtils.isNotEmpty(col)) {
sb.append(CsjLogConst.SIGN_COL + addlrBracketsM(col,true) );
}
if (CmnStrUtils.isNotEmpty(content)) {
sb.append(CsjLogConst.SIGN_CONTENT + addlrBracketsM(content,true) );
}
return addlrBracket_M_L_JP(sb.toString(),true);
}
public static String addlrBracketsM(String str,boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.SIGN_BRACKETS_M_L + str + CsjConst.SIGN_BRACKETS_M_R;
}
public static String addlrBracket_M_L_JP(String str, boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.Z_SIGN_BRACKETS_M_L_JP + str + CsjConst.Z_SIGN_BRACKETS_M_R_JP;
}
public static String addlrBracketsS(String str, boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.SIGN_BRACKETS_S_L + str + CsjConst.SIGN_BRACKETS_S_R;
}
/**
* @param writer
* @param line
*/
public static void writeLine(BufferedWriter writer, String line) throws Throwable {
try {
writer.write(line);
writer.newLine();
writer.flush();
} catch (Throwable e) {
throw e;
}
}
/**
* @param writer
* @param line
*/
public static void writeLineWithConsole(BufferedWriter writer, String line) throws Throwable {
try {
writer.write(line);
writer.newLine();
writer.flush();
System.out.println(line);
} catch (Throwable e) {
throw e;
}
}
/**
* @param writer
* @throws IOException
*/
public static void close(BufferedWriter writer) throws Throwable {
// TODO Auto-generated method stub
try {
if (writer!=null) {
writer.close();
writer=null;
}
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnNumUtils.java
/**
*
*/
package org.mydbsee.common;
/**
* @author Think
*
*/
public class CmnNumUtils {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* support Numeric format:<br>
* "33" "+33" "033.30" "-.33" ".33" " 33." " 000.000 "
*
* @param str String
* @return boolean
*/
public static boolean isNumeric(String str) {
int begin = 0;
boolean once = true;
if (str == null || str.trim().equals("")) {
return false;
}
str = str.trim();
if (str.startsWith("+") || str.startsWith("-")) {
if (str.length() == 1) {
// "+" "-"
return false;
}
begin = 1;
}
for (int i = begin; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
if (str.charAt(i) == '.' && once) {
// '.' can only once
once = false;
} else {
return false;
}
}
}
if (str.length() == (begin + 1) && !once) {
// "." "+." "-."
return false;
}
return true;
}
/**
* support Integer format:<br>
* "33" "003300" "+33" " -0000 "
*
* @param str String
* @return boolean
*/
public static boolean isInteger(String str) {
int begin = 0;
if (str == null || str.trim().equals("")) {
return false;
}
str = str.trim();
if (str.startsWith("+") || str.startsWith("-")) {
if (str.length() == 1) {
// "+" "-"
return false;
}
begin = 1;
}
for (int i = begin; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* use Exception
* support Numeric format:<br>
* "33" "+33" "033.30" "-.33" ".33" " 33." " 000.000 "
*
* @param str String
* @return boolean
*/
public static boolean isNumericEx(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
/**
* use Exception
* support less than 11 digits(<11)<br>
* support Integer format:<br>
* "33" "003300" "+33" " -0000 " "+ 000"
*
* @param str String
* @return boolean
*/
public static boolean isIntegerEx(String str) {
str = str.trim();
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException ex) {
if (str.startsWith("+")) {
return isIntegerEx(str.substring(1));
}
return false;
}
}
// 判断是否是整数
public static boolean isNumericReg(String s) {
if (CmnStrUtils.isNotEmpty(s))
return s.matches("^[0-9]*$");
else
return false;
}
// 判断传递来的是否是数字
public static int checkID(String s) {
if ((s == null) || (s.length() == 0) || !s.matches("^[0-9]*$")) {
return 0;
} else {
if (s.length() < 10) {
return Integer.parseInt(s);
} else {
return 0;
}
}
}
// 判断传递来的是否是字符串
public static String checkString(String s) {
if ((s == null) || (s.length() == 0) || s.matches("^[0-9]*$")) {
return "";
} else {
return s;
}
}
}
-------C:\aa\common\CmnPoiUtils.java
package org.mydbsee.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import jp.co.csj.tools.utils.common.CsjPath;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.db.core.XlsTblPara;
import jp.co.csj.tools.utils.msg.dbtools.CsjDbToolsMsg;
import jp.co.csj.tools.utils.poi.core.CsjCellInfo;
import jp.co.csj.tools.utils.poi.core.CsjColInfo;
import jp.co.csj.tools.utils.poi.core.CsjDbCellStyle;
import jp.co.csj.tools.utils.poi.core.CsjPatr;
import jp.co.csj.tools.utils.poi.core.CsjPosition;
import jp.co.csj.tools.utils.poi.core.CsjRowInfo;
import jp.co.csj.tools.utils.poi.core.CsjSchedual;
import jp.co.csj.tools.utils.poi.core.CsjSheetInfo;
import jp.co.csj.tools.utils.reg.RegConstStr;
public class CmnPoiUtils {
public static final int S_CELL_MAX_NUM_2007 = 1048576;
public static final int S_CELL_MAX_NUM_2003 = 32767;
/**
* Remove a row by its index
* @param sheet a Excel sheet
* @param rowIndex a 0 based index of removing row
* @throws Throwable
*/
public static void removeRow(Sheet sheet, int rowIndex) throws Throwable {
try {
int lastRowNum=sheet.getLastRowNum();
if(rowIndex>=0&&rowIndex<lastRowNum)
sheet.shiftRows(rowIndex+1,lastRowNum,-1);//将行号为rowIndex+1一直到行号为lastRowNum的单元格全部上移一行,以便删除rowIndex行
if(rowIndex==lastRowNum){
Row removingRow=sheet.getRow(rowIndex);
if(removingRow!=null)
sheet.removeRow(removingRow);
}
} catch (Throwable e) {
throw e;
}
}
public static void insertRow(Sheet sheet, int starRow, int rows,boolean isWithContent) throws Throwable {
try {
if (rows <= 0) {
return;
}
if (starRow + 1 == sheet.getLastRowNum()) {
CmnPoiUtils.setCellValue(sheet, starRow + 2, 0, " ");
}
// 选择一个区域,从startRow+1直到最后一行
sheet.shiftRows(starRow + 1, sheet.getLastRowNum(), rows, true, false);
starRow = starRow - 1;
for (int i = 0; i < rows; i++) {
Row sourceRow = null;
Row targetRow = null;
Cell sourceCell = null;
Cell targetCell = null;
int m;
starRow = starRow + 1;
sourceRow = sheet.getRow(starRow);
if (sourceRow == null) {
sourceRow = sheet.createRow(starRow);
}
// 從start創建新的一行
targetRow = sheet.createRow(starRow + 1);
targetRow.setHeight(sourceRow.getHeight());
// 处理刚刚创建的一行
for (m = sourceRow.getFirstCellNum(); m < sourceRow.getLastCellNum(); m++) {
sourceCell = sourceRow.getCell(m);
targetCell = targetRow.createCell(m);
if (sourceCell!=null &&targetCell!=null) {
// 风格一样
targetCell.setCellStyle(sourceCell.getCellStyle());
targetCell.setCellType(sourceCell.getCellType());
if (isWithContent) {
targetCell.setCellValue(getCellStr(sourceCell));
}
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, String str, CellStyle cs) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (cs != null) {
cell.setCellStyle(cs);
cell.setCellValue(str);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, String str, CellStyle cs, CellStyle csBlank) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (CmnStrUtils.isEmpty(str)) {
cell.setCellStyle(csBlank);
} else {
cell.setCellStyle(cs);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, XlsTblPara xlsTblPara, CsjDbCellStyle cellStyle) throws Throwable {
Cell cell = null;
try {
if (CmnStrUtils.isEmpty(xlsTblPara.getParaVal())) {
cell = setCellValue(sheet, rowPos, colNum, xlsTblPara.getParaVal());
cell.setCellStyle(cellStyle.getCsRecordBlank());
} else {
cell = setCellValue(sheet, rowPos, colNum, xlsTblPara.getParaVal());
cell.setCellStyle(cellStyle.getCsRecordStr());
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, RichTextString str,
CellStyle cs) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (cell != null) {
cell.setCellStyle(cs);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValue(Sheet sheet, int rowNum, int colNum, RichTextString val) throws Throwable {
Cell cell = null;
try {
cell = getOrCreateCell(sheet, rowNum, colNum);
if (CmnStrUtils.isNotEmpty(val) && getExcelMaxRowNum(sheet) < val.length()) {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000088));
}
if (cell != null) {
cell.setCellValue(val);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValue(Sheet sheet, int rowNum, int colNum, String val) throws Throwable {
Cell cell = null;
try {
cell = getOrCreateCell(sheet, rowNum, colNum);
if (CmnStrUtils.isNotEmpty(val) && getExcelMaxRowNum(sheet) < val.length()) {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000088));
}
if (cell != null) {
cell.setCellValue(val);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
private static int getExcelMaxRowNum(Sheet sheet) throws Throwable{
int maxRow = 0;
try {
if (sheet instanceof HSSFSheet) {
maxRow = S_CELL_MAX_NUM_2003;
} else {
maxRow = S_CELL_MAX_NUM_2007;
}
} catch (Throwable e) {
throw e;
}
return maxRow;
}
/**
* @param sheet
* @param rowNum
* @param colNum
* @return
*/
public static Cell getOrCreateCell(Sheet sheet, int rowNum, int colNum) throws Throwable {
Cell cell = null;
try {
if (sheet == null) {
return null;
}
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
cell = row.getCell(colNum);
if (cell == null) {
cell = row.createCell(colNum);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static List<String>
getCellContents(File inFile, String fromSheetName) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
String str = CsjConst.EMPTY;
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
fileInputStream.close();
printSheet(inFile.getAbsolutePath(), sheet);
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(File inFile,
String fromSheetName, int rowNum) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
String str = CsjConst.EMPTY;
for (Row row : sheet) {
if (row.getRowNum() == rowNum) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
}
fileInputStream.close();
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(str);
}
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, int colBegin,boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
if (cell.getColumnIndex()<colBegin) {
continue;
}
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(str);
}
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static CsjCellInfo getCellFontByContent(Row row, String str,boolean checkStrikeOut) throws Throwable {
CsjCellInfo cellInfo =null;
try {
if (row != null) {
for (Cell cell : row) {
if (str.equals(getCellContent(cell, checkStrikeOut))) {
cellInfo = getCellInfo(cell);
break;
}
}
}
} catch (Throwable e) {
throw e;
}
return cellInfo;
}
public static Font createCellFont(Workbook wb, CsjCellInfo cellInfo) {
Font ft = wb.createFont();
Font f = cellInfo.getFont();
ft.setBold(f.getBold());
ft.setBoldweight(f.getBoldweight());
ft.setCharSet(f.getCharSet());
ft.setColor(f.getColor());
ft.setFontHeight(f.getFontHeight());
ft.setFontHeightInPoints(f.getFontHeightInPoints());
ft.setFontName(f.getFontName());
ft.setItalic(f.getItalic());
ft.setStrikeout(f.getStrikeout());
ft.setTypeOffset(f.getTypeOffset());
ft.setUnderline(f.getUnderline());
return ft;
}
public static CellStyle createCellStyle(Workbook wb,CsjCellInfo cellInfo) {
CellStyle retCs = wb.createCellStyle();
if (cellInfo == null) {
return null;
}
CellStyle cs =cellInfo.getCs();
if (cs == null) {
return null;
}
retCs.setAlignment(cs.getAlignment());
retCs.setBorderBottom(cs.getBorderBottom());
retCs.setBorderLeft(cs.getBorderLeft());
retCs.setBorderRight(cs.getBorderRight());
retCs.setBorderTop(cs.getBorderTop());
retCs.setBottomBorderColor(cs.getBottomBorderColor());
retCs.setDataFormat(cs.getDataFormat());
retCs.setFillBackgroundColor(cs.getFillBackgroundColor());
retCs.setFillForegroundColor(cs.getFillForegroundColor());
retCs.setFillPattern(cs.getFillPattern());
retCs.setFont(createCellFont(wb, cellInfo));
retCs.setHidden(cs.getHidden());
retCs.setIndention(cs.getIndention());
retCs.setLeftBorderColor(cs.getLeftBorderColor());
retCs.setLocked(cs.getLocked());
retCs.setRightBorderColor(cs.getRightBorderColor());
retCs.setRotation(cs.getRotation());
retCs.setShrinkToFit(cs.getShrinkToFit());
retCs.setTopBorderColor(cs.getTopBorderColor());
retCs.setVerticalAlignment(cs.getVerticalAlignment());
retCs.setWrapText(cs.getWrapText());
// if (cell instanceof HSSFCell) {
// HSSFCell c = (HSSFCell)cell;
// font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
// } else {
// XSSFCell c = (XSSFCell)cell;
// font = c.getCellStyle().getFont();
// }
//
// Font font = ((HSSFCellStyle)retCs).getFont((HSSFWorkbook)wb);
// font.getBold();
return retCs;
}
public static void testgetCellContents(File inFile, String fromSheetName,
int rowNum) throws Throwable {
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
removeRow(sheet, rowNum);
fileInputStream.close();
FileOutputStream fileOut = new FileOutputStream("d:\\aaa1.xls");
wb.write(fileOut);
fileOut.close();
} catch (Throwable e) {
throw e;
}
}
public static LinkedHashMap<Integer,String> getCellContentMaps(Row row, boolean checkStrikeOut) throws Throwable {
LinkedHashMap<Integer,String> map = new LinkedHashMap<Integer, String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
map.put(cell.getRowIndex(), str);
}
}
}
} catch (Throwable e) {
throw e;
}
return map;
}
public static List<String> getCellContents(Sheet sheet, int col, int rowMin,int rowMax, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Row row: sheet) {
int rowNum = row.getRowNum();
if (rowMin<=rowNum&& rowNum<=rowMax) {
str = getCellContent(row, col, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, int preCol, int endCol, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
int cellCol = cell.getColumnIndex();
if (preCol <= cellCol && cellCol <= endCol) {
str = getCellContent( cell, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static LinkedHashMap<String,String> getCellContentsMap(Row row, boolean checkStrikeOut) throws Throwable {
LinkedHashMap<String,String> retMap = new LinkedHashMap<String,String>();
try {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retMap.put(String.valueOf(cell.getColumnIndex()), str);
}
}
} catch (Throwable e) {
throw e;
}
return retMap;
}
public static String getCellContent(Row row, int colIndex, boolean checkStrikeOut) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (row == null) {
return CsjConst.EMPTY;
}
Cell cell = row.getCell(colIndex);
if(cell == null) {
return CsjConst.EMPTY;
}
retStr = getCellContent(cell, checkStrikeOut);
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static List<String> getCellContents(Sheet sheet, boolean checkStrikeOut) {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retList;
}
public static void clearCellContents(Sheet sheet,int rowMin,int rowMax,int colMin,int colMax) {
try {
for (Row row : sheet) {
if (row.getRowNum()<=rowMin||(rowMax>=0 && row.getRowNum()>=rowMax)) {
continue;
}
for (Cell cell : row) {
if (cell.getColumnIndex()<=colMin||(colMax>=0 && cell.getColumnIndex()>=colMax)) {
continue;
}
cell.setCellValue("");
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
}
public static HashSet<String> getCellContentsMap(String filePath, String sheetNm,boolean checkStrikeOut)throws Throwable {
return getCellContentsMap(new File(filePath),sheetNm,checkStrikeOut);
}
public static HashSet<String> getCellContentsMap(File f, String sheetNm, boolean checkStrikeOut)throws Throwable {
HashSet<String> sSet = new HashSet<String>();
try {
Workbook wb;
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
String str = CsjConst.EMPTY;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
if (CmnStrUtils.isNotEmpty(sheetNm)) {
if (sheet.getSheetName().equals(sheetNm) == false) {
continue;
}
}
for (Row row : sheet) {
for (Cell cell : row) {
str = CmnStrUtils.lrTrimSpace(getCellContent( cell, false));
if (CmnStrUtils.isNotEmpty(str)) {
sSet.add(CmnStrUtils.toLowOrUpStr(str));
}
}
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
return sSet;
}
public static List<String> getCellContents(String filePath, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
File f = new File(filePath);
if (f.isFile() == false) {
return retList;
}
FileInputStream fs = new FileInputStream(f);
Workbook wb ;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
String str = CsjConst.EMPTY;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
return retList;
}
public static String getCellContent(Sheet sheet, int rowIndex, int colIndex, boolean checkStrikeOut) throws Throwable {
String retVal = CsjConst.EMPTY;
try {
if (sheet != null) {
Row row = sheet.getRow(rowIndex);
retVal = getCellContent(row, colIndex, checkStrikeOut);
}
} catch (Throwable e) {
throw e;
}
return retVal;
}
public static String getCellContent(String fileAbsPath,String sheetNm, int rowIndex, int colIndex, boolean checkStrikeOut) throws Throwable {
FileInputStream fileIn = null;
Workbook wb;
try {
fileIn = new FileInputStream(new File(fileAbsPath));
if (CmnStrUtils.isEndByIgnor(fileAbsPath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileIn);
} else {
wb = new XSSFWorkbook(fileIn);
}
} catch (Throwable e) {
throw e;
} finally {
if (fileIn != null) {
fileIn.close();
}
}
return getCellContent(wb.getSheet(sheetNm),rowIndex, colIndex, checkStrikeOut);
}
public static String getCellAreaContents(Sheet sheet, int rowBeginIndex, int rowEndIndex, int colBeginIndex,
int colEndIndex, List<String> strList, boolean checkStrikeOut) {
StringBuffer retSb = new StringBuffer();
try {
for (Row row : sheet) {
if (rowBeginIndex <= row.getRowNum() && row.getRowNum() <= rowEndIndex) {
for (Cell cell : row) {
if (colBeginIndex <= cell.getColumnIndex() && cell.getColumnIndex() <= colEndIndex) {
String val = getCellContent( cell, checkStrikeOut);
retSb.append(val);
strList.add(val);
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retSb.toString();
}
public static String getCellContent(Cell cell, boolean checkStrikeOut) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (null == cell) {
return retStr;
}
if (checkStrikeOut) {
Font font;
if (cell instanceof HSSFCell) {
HSSFCell c = (HSSFCell)cell;
font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
if (font.getStrikeout()) {
return retStr;
}
} else if (cell instanceof XSSFCell) {
XSSFCell c = (XSSFCell)cell;
font = c.getCellStyle().getFont();
if (font.getStrikeout()) {
return retStr;
}
// XSSFRichTextString richTextStr = c.getRichStringCellValue();
//
// StringBuffer sb = new StringBuffer();
// char ch[] = richTextStr.getString().toCharArray();
// for (int i = 0; i < richTextStr.length(); i++) {
// font = richTextStr.getFontAtIndex(i);
// if (font != null && font.getStrikeout()) {
//
// } else {
// sb.append(ch[i]);
// }
// }
// retStr = sb.toString();
// return retStr;
}
}
retStr = getCellStr(cell);
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static CsjCellInfo getCellInfo(Cell cell) throws Throwable {
if (null == cell) {
return null;
}
CsjCellInfo retVal = null;
try {
retVal = new CsjCellInfo(getCellStr(cell),cell.getRowIndex(),cell.getColumnIndex());
Font font = null;
if (cell instanceof HSSFCell) {
HSSFCell c = (HSSFCell)cell;
font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
} else {
XSSFCell c = (XSSFCell)cell;
font = c.getCellStyle().getFont();
}
CellStyle cs = cell.getCellStyle();
retVal.setCs(cs);
retVal.setFont(font);
} catch (Throwable e) {
throw e;
}
return retVal;
}
/**
* @param cell
* @param retStr
* @return
* @throws Throwable
*/
private static String getCellStr(Cell cell) throws Throwable {
String retStr = "";
try {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
retStr = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} else {
retStr = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
retStr = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
try {
if (DateUtil.isCellDateFormatted(cell)) {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} else {
retStr = String.valueOf(cell.getNumericCellValue());
retStr = CmnStrUtils.getNumberByTrimDot0(retStr);
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
try {
retStr = cell.getRichStringCellValue().getString();
} catch (Throwable e1) {
CmnLog.logger.info(e1.getMessage());
try {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} catch (Throwable e2) {
retStr = cell.getCellFormula();
CmnLog.logger.info(e2.getMessage());
}
}
}
break;
default:
// System.out.println();
}
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static void setCellComment(Cell cell, RichTextString content, String author) throws Throwable {
try {
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
Drawing patr = cell.getSheet().createDrawingPatriarch();
//anchor defines size and position of the comment in worksheet
Comment comment = null;
if (cell instanceof HSSFCell) {
comment = patr.createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
// set text in the comment
comment.setString(content);
} else if (cell instanceof XSSFCell) {
comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
XSSFRichTextString xssfRichTextString = new XSSFRichTextString(content.getString());
comment.setString(xssfRichTextString);
}
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell
comment.setAuthor(author);
// The first way to assign comment to a cell is via XSSFCell.setCellComment method
cell.setCellComment(comment);
} catch (Throwable e) {
throw e;
}
}
public static void setCellCommentBig(Cell cell, RichTextString content, String author) throws Throwable {
try {
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
Drawing patr = cell.getSheet().createDrawingPatriarch();
//anchor defines size and position of the comment in worksheet
Comment comment = null;
if (cell instanceof HSSFCell) {
comment = patr.createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 8, 17));
// set text in the comment
comment.setString(content);
} else if (cell instanceof XSSFCell) {
comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 8, 17));
XSSFRichTextString xssfRichTextString = new XSSFRichTextString(content.getString());
comment.setString(xssfRichTextString);
}
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell
comment.setAuthor(author);
// The first way to assign comment to a cell is via XSSFCell.setCellComment method
cell.setCellComment(comment);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param csjPart
* @throws Throwable
*/
public static void setCommentByCell(Cell cell, String content, Font font, CsjPatr csjPart,
boolean isVisable, String user) throws Throwable {
// Create the drawing patriarch. This is the top level container for all
// shapes including cell comments.
try {
Comment comment = null;
RichTextString string;
if (cell instanceof HSSFCell) {
comment = csjPart.getPatr().createCellComment(
new HSSFClientAnchor(0, 0, 0, 0, csjPart.getCol1(), csjPart.getRow1(), csjPart.getCol2(), csjPart
.getRow2()));
string = new HSSFRichTextString(content);
string.applyFont(font);
comment.setString(string);
} else if (cell instanceof XSSFCell) {
comment = csjPart.getPatr().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, csjPart.getCol1(), csjPart.getRow1(), csjPart.getCol2(), csjPart
.getRow2()));
string = new XSSFRichTextString(content);
string.applyFont(font);
comment.setString(string);
}
// modify background color of the comment
//comment.setFillColor(204, 236, 255);
comment.setVisible(isVisable); // by default comments are hidden. This
// one is always visible.
if (CmnStrUtils.isNotEmpty(user)) {
comment.setAuthor(user);
}
/**
* The second way to assign comment to a cell is to implicitly specify
* its row and column. Note, it is possible to set row and column of a
* non-existing cell. It works, the comment is visible.
*/
comment.setRow(cell.getRowIndex());
comment.setColumn(cell.getColumnIndex());
} catch (Throwable e) {
throw e;
}
}
public static void setColorForDif(RichTextString oldRichStr,
RichTextString newRichStr, Font sFontRed, String enCode) {
String oldStr = oldRichStr.getString();
String newStr = newRichStr.getString();
List<CsjPosition> oldPositionList = new ArrayList<CsjPosition>();
List<CsjPosition> newPositionList = new ArrayList<CsjPosition>();
try {
byte[] oldByteArr = oldStr.getBytes(enCode);
byte[] newByteArr = newStr.getBytes(enCode);
int oldLen = oldStr.length();//oldByteArr.length;
int newLen = newStr.length();//ByteArr.length;
int minLen = oldLen<newLen? oldLen : newLen;
for (int i = 0; i < minLen; i++) {
if (oldStr.charAt(i) != newStr.charAt(i)) {
oldPositionList.add(new CsjPosition(i, i+1));
newPositionList.add(new CsjPosition(i, i+1));
}
}
if (minLen < oldLen) {
oldPositionList.add(new CsjPosition(minLen, oldLen));
} else if (minLen < newLen) {
newPositionList.add(new CsjPosition(minLen, newLen));
}
for (CsjPosition pos : oldPositionList) {
oldRichStr.applyFont(pos.getStartPos(), pos.getEndPos(), sFontRed);
}
for (CsjPosition pos : newPositionList) {
newRichStr.applyFont(pos.getStartPos(), pos.getEndPos(), sFontRed);
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
System.out.println("csj:color can't use!");
}
}
/*
* /**
*
* @param logger
*
* @param sheet
*/
public static void printSheet(String path, Sheet sheet) throws Throwable {
try {
for (Row row : sheet) {
for (Cell cell : row) {
String val = getCellContent((Cell) cell, true);
if (CmnStrUtils.isNotEmpty(val)) {
CmnLog.logger.error("file path:["+path+"]sheet:["+sheet.getSheetName()+"]row:[" + row.getRowNum() + "]col:[" + cell.getColumnIndex() + "]val:["
+ getCellContent( cell, true) + "]");
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static void printSheet(String filePath) throws Throwable {
try {
File f = new File(filePath);
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.toLowOrUpStr(filePath).endsWith(CmnStrUtils.toLowOrUpStr(CsjConst.EXCEL_DOT_XLS_1997))) {
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
printSheet(f.getAbsolutePath(),wb.getSheetAt(i));
}
} else if (CmnStrUtils.toLowOrUpStr(filePath).endsWith(CmnStrUtils.toLowOrUpStr(CsjConst.EXCEL_DOT_XLSX_2007))) {
XSSFWorkbook wb = new XSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
printSheet(f.getAbsolutePath(),wb.getSheetAt(i));
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetWithOutNms(Workbook wb, Set<String> sheetNmSet) throws Throwable {
try {
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (sheetNmSet.contains(snm)) {
continue;
}
set.add(snm);
}
deleteSheetNm(wb, set);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetWithOutNm(Workbook wb, String sheetNm) throws Throwable {
try {
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (sheetNm.equals(snm)) {
continue;
}
set.add(snm);
}
deleteSheetNm(wb, set);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetNm(Workbook wb, HashSet<String> set) throws Throwable {
try {
Iterator iterator = set.iterator();
while(iterator.hasNext()){
String sheetNm = iterator.next().toString();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (snm.equals(sheetNm)) {
wb.removeSheetAt(i);
break;
}
}
}
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteWithOutSheetNm(Workbook wb, HashSet<String> set) throws Throwable {
try {
HashSet<String> deleteSheetNmSet = new HashSet<String>();
for (int i = 0; i <wb.getNumberOfSheets(); i++) {
String sheetNm = wb.getSheetAt(i).getSheetName();
if (!set.contains(sheetNm)) {
deleteSheetNmSet.add(sheetNm);
}
}
deleteSheetNm(wb, deleteSheetNmSet);
} catch (Throwable e) {
throw e;
}
}
/**
* @param cell
* @return
* @throws Throwable
*/
public static String getCellComment(Cell cell) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (cell == null || cell.getCellComment() == null || cell.getCellComment().getString() == null) {
} else {
retStr = cell.getCellComment().getString().getString();
}
} catch (Throwable e) {
throw e;
}
return retStr;
}
/**
* @param xlsPath
* @return
* @throws Throwable
* @throws IOException
* @throws FileNotFoundException
*/
public static List<String> getSheetNms(String xlsPath,
List<String> sheetList) throws Throwable {
Workbook wb = null;
FileInputStream fs = null;
try {
File f = new File(xlsPath);
fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(xlsPath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
int sheetSum = wb.getNumberOfSheets();
for (int i = 0; i < sheetSum; i++) {
Sheet sheet = wb.getSheetAt(i);
sheetList.add(sheet.getSheetName());
}
wb.close();
fs.close();
} catch (Throwable e) {
throw e;
}
return sheetList;
}
/**
* @param xlsPath
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static void getSheetNmsAndFiles(String xlsPath,HashSet<String> sheetSet, HashMap<String,Sheet> sheetMap) throws Throwable {
Workbook wb;
LinkedList<File> tFileList = CmnFileUtils.getExcelFileByAbsPath(xlsPath, true);
for (File f : tFileList) {
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
int sheetSum = wb.getNumberOfSheets();
for (int i = 0; i < sheetSum; i++) {
Sheet sheet = wb.getSheetAt(i);
sheetMap.put(CmnStrUtils.toLowOrUpStr(sheet.getSheetName()), sheet);
sheetSet.add(CmnStrUtils.toLowOrUpStr(sheet.getSheetName()));
}
fs.close();
}
}
/**
* @param wb
* @param map
*/
public static void deleteSheetByNm(Workbook wb, HashSet<String> set, boolean isDelSheetNmInSet) {
for (String sheetNm : set) {
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (isDelSheetNmInSet) {
if (snm.equals(sheetNm)) {
wb.removeSheetAt(i);
break;
}
} else {
if (snm.equals(sheetNm) == false) {
wb.removeSheetAt(i);
break;
}
}
}
}
}
public static void getXlsSheetsToOneXls(String filePath,String xlsNmPath,String xlsNm) throws Throwable {
LinkedList<File> fileList = CmnFileUtils.getFilesListReg(filePath, true,RegConstStr.EXCEL_REG_DOT);
FileInputStream fileIn = new FileInputStream(CsjPath.s_file_table_temp);
XSSFWorkbook wbOut = new XSSFWorkbook(fileIn);
Workbook wb;
for (File f : fileList) {
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet fromSheet = wb.getSheetAt(i);
String toSheetNm = fromSheet.getSheetName();
Sheet toSheet = wbOut.createSheet(toSheetNm);
// copySheet(fromSheet, toSheet);
}
fs.close();
}
fileIn.close();
writeXls(wbOut,xlsNmPath,xlsNm);
}
public static Workbook getWorkBook(String filePath) throws Throwable {
File f = new File(filePath);
FileInputStream fileIn = new FileInputStream(f);
Workbook wb;
if (CmnStrUtils.isEndByIgnor(f.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileIn);
} else {
wb = new XSSFWorkbook(fileIn);
}
return wb;
}
public static void writeXls(Workbook wb,String xlsNmPath,String xlsNm) throws Throwable {
FileOutputStream fileOut = null;
File f = new File(xlsNmPath);
f.mkdirs();
String filePath = xlsNmPath+ xlsNm+ CsjConst.EXCEL_DOT_XLSX_2007;
fileOut = new FileOutputStream(filePath);
wb.write(fileOut);
fileOut.close();
}
public static void main(String[] args) {
try {
// FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\Think\\Desktop\\日本人姓氏大全集.xls"));
// XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
Workbook wb = getWorkBook("D:\\IDE\\eclipse-jee-oxygen-M4-win32\\eclipse\\workspace\\CsjToolsPic\\dbInfo\\template\\TableStructTemp.xlsx");
Sheet st = wb.getSheetAt(0);
for (Row row : st) {
for (Cell cell : row) {
System.out.println(getCellContent(cell, true));
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public static CsjSheetInfo getSheetContents(String filePath,String sheetNm,boolean checkStrikeOut) throws Throwable {
CsjSheetInfo csjSheetInfo =new CsjSheetInfo();
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
} else {
wb = new XSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
}
csjSheetInfo.setFilePath(filePath);
fileInputStream.close();
return csjSheetInfo;
}
public static List<List<String>> getSchedualContents(String filePath,String sheetNm,boolean checkStrikeOut) throws Throwable {
List<List<String>> retLst = new ArrayList<List<String>>();
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(sheetNm);
for (Row row:sheet) {
List<String> strLst = new ArrayList<String>();
for (Cell cell : row) {
strLst.add(getCellContent(cell, false));
}
retLst.add(strLst);
}
fileInputStream.close();
return retLst;
}
public static void schedualXlsReplace(String filePath,String fileOutPath,String sheetNm,List<List<String>> strLst) throws Throwable{
try {
File file = new File(filePath);
FileInputStream fileIn = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(fileIn);
for (int i = wb.getNumberOfSheets()-1; i >=0 ; i--) {
wb.removeSheetAt(i);
}
wb.createSheet(sheetNm);
Sheet st = wb.getSheet(sheetNm);
for (int i = 0; i < strLst.size(); i++) {
List<String> lst = strLst.get(i);
for (int j = 0; j < lst.size(); j++) {
setCellValue(st, i, j, lst.get(j));
}
}
FileOutputStream fileOut = new FileOutputStream(fileOutPath);
wb.write(fileOut);
fileOut.close();
fileIn.close();
} catch (Throwable e) {
throw e;
}
}
public static Map<Integer,String> getSheetContents(String filePath,String sheetNm,int col,int rowStart,int rowEnd) throws Throwable {
Map<Integer,String> retMap = new HashMap<Integer, String>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath,CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(sheetNm);
for (int i = rowStart; i <=rowEnd; i++) {
Row row = sheet.getRow(i);
retMap.put(i-rowStart, getCellContent(row, col, false));
}
fileInputStream.close();
return retMap;
}
public static Map<String, TreeMap<String,CsjSchedual>> getScheduals(String filePath, String sheetName)throws Throwable {
Map<String, TreeMap<String,CsjSchedual>> hashMap = new LinkedHashMap<String, TreeMap<String,CsjSchedual>>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet st = wb.getSheetAt(i);
if (CmnStrUtils.isNotEmpty(sheetName)&& st.getSheetName().equals(sheetName) == false) {
continue;
}
String sheetNameCurrent = st.getSheetName();
TreeMap<String,CsjSchedual> treeMap = new TreeMap<String, CsjSchedual>();
for (Row row : st) {
if (row.getRowNum()<2) {
continue;
}
CsjSchedual schedual = new CsjSchedual();
schedual.setNo(getCellContent(row, 1, false));
schedual.setRunType(getCellContent(row, 2, false));
schedual.setWaitSecond(getCellContent(row, 3, false));
schedual.setRunFile(getCellContent(row, 4, false));
// -------------
schedual.setFromFolder(getCellContent(row, 5, false));
schedual.setFromFile(getCellContent(row, 6, false));
schedual.setToFolder(getCellContent(row, 7, false));
schedual.setToFile(getCellContent(row, 8, false));
schedual.setDbInExcelPath(getCellContent(row, 9, false));
schedual.setDbInSheet(getCellContent(row, 10, false));
schedual.setDbInTblNm(getCellContent(row, 11, false));
schedual.setDbInIsContain(getCellContent(row, 12, false));
schedual.setDbInResultPath(getCellContent(row, 13, false));
// -------------
schedual.setSyncExcelPath(getCellContent(row, 14, false));
schedual.setSyncExcelSheet(getCellContent(row, 15, false));
// -------------
schedual.setDbOutAllTableOneSheet(getCellContent(row, 16, false));
schedual.setDbOutAllTableResultPath(getCellContent(row, 17, false));
// -------------
schedual.setDbOutOneTableNm(getCellContent(row, 18, false));
schedual.setDbOutOneTableColNm(getCellContent(row, 19, false));
schedual.setDbOutOneTableColCharLike(getCellContent(row, 20, false));
schedual.setDbOutOneTableColNumMin(getCellContent(row, 21, false));
schedual.setDbOutOneTableColNumMax(getCellContent(row, 22, false));
schedual.setDbOutOneTableColDateMin(getCellContent(row, 23, false));
schedual.setDbOutOneTableColDateMax(getCellContent(row, 24, false));
schedual.setDbOutOneTableResultPath(getCellContent(row, 25, false));
// -------------
schedual.setDbOutSqlType(getCellContent(row, 26, false));
schedual.setDbOutSqlPath(getCellContent(row, 27, false));
schedual.setDbOutSqlResultPath(getCellContent(row, 28, false));
schedual.setDbOutConfigPath(getCellContent(row, 29, false));
schedual.setDbOutConfigResultPath(getCellContent(row, 30, false));
// -------------
schedual.setCompareStructOldPath(getCellContent(row, 31, false));
schedual.setCompareStructNewPath(getCellContent(row, 32, false));
schedual.setCompareStructResultPath(getCellContent(row, 33, false));
// -------------
schedual.setCompareDataPath(getCellContent(row, 34, false));
schedual.setCompareDataType(getCellContent(row, 35, false));
schedual.setCompareDbOut(getCellContent(row, 36, false));
schedual.setCompareOnlyChange(getCellContent(row, 37, false));
schedual.setCompareResultPath(getCellContent(row, 38, false));
// -------------
schedual.setTblStructOutIniPath(getCellContent(row, 39, false));
schedual.setTblStructOutIsCompare(getCellContent(row, 40, false));
schedual.setTblStructOutComparePath(getCellContent(row, 41, false));
schedual.setTblStructOutResultPath(getCellContent(row, 42, false));
// -------------
schedual.setDbChangeType(getCellContent(row, 43, false));
schedual.setDbChangeResultPath(getCellContent(row, 44, false));
// -------------
schedual.setTblScriptOutType(getCellContent(row, 45, false));
schedual.setTblScriptFromPath(getCellContent(row, 46, false));
schedual.setTblScriptResultPath(getCellContent(row, 47, false));
// -------------
schedual.setCreateTblTemplateNm(getCellContent(row, 48, false));
schedual.setCreateTblFromFile(getCellContent(row, 49, false));
schedual.setCreateTblNm(getCellContent(row, 50, false));
schedual.setCreateTblType(getCellContent(row, 51, false));
schedual.setCreateResultPath(getCellContent(row, 52, false));
// -------------
schedual.setOutputTxtAble(getCellContent(row, 53, false));
schedual.setOutputTxtSplit(getCellContent(row, 54, false));
schedual.setOutputTxtCr(getCellContent(row, 55, false));
// ----------------------------------------------------
schedual.setWaitFile(getCellContent(row, 78, false));
schedual.setWaitFileSecond(getCellContent(row, 79, false));
// ----------------------------------------------------
schedual.setDelFolderPath(getCellContent(row, 80, false));
schedual.setDelFileNmReg(getCellContent(row, 81, false));
// ----------------------------------------------------
schedual.setConfigFile(getCellContent(row, 82, false));
schedual.setDbType(getCellContent(row, 83, false));
schedual.setTableSheet(getCellContent(row, 84, false));
schedual.setSplitData(getCellContent(row, 85, false));
schedual.setRecordNum(getCellContent(row, 86, false));
schedual.setExcelType(getCellContent(row, 87, false));
schedual.setInDb(getCellContent(row, 88, false));
schedual.setInLog(getCellContent(row, 89, false));
schedual.setGenrateSql(getCellContent(row, 90, false));
schedual.setInsertAble(getCellContent(row, 91, false));
schedual.setTblNumDisplay(getCellContent(row, 92, false));
schedual.setErrorSkip(getCellContent(row, 93, false));
schedual.setTblClear(getCellContent(row, 94, false));
schedual.setCheckExeType(getCellContent(row, 95, false));
schedual.setLogicCheck(getCellContent(row, 96, false));
schedual.setEncode(getCellContent(row, 97, false));
schedual.setExeType(getCellContent(row, 98, false));
schedual.setBatch(getCellContent(row, 99, false));
///-------------
schedual.setMailFolderPath(getCellContent(row, 100, false));
schedual.setMailTo(getCellContent(row, 101, false));
schedual.setMailTitle(getCellContent(row, 102, false));
schedual.setMailText(getCellContent(row, 103, false));
schedual.setMailZipNm(getCellContent(row, 104, false));
schedual.setMailZipPwd(getCellContent(row, 105, false));
if (CmnStrUtils.isNotEmpty(schedual.getRunTypeStr()) &&CmnStrUtils.isNotEmpty(schedual.getNo()) ) {
treeMap.put(schedual.getNo(), schedual);
}
}
hashMap.put(filePath+CmnLog5j.addlrBracketsM(sheetNameCurrent, false), treeMap);
}
fileInputStream.close();
return hashMap;
}
public static HashMap<String, CsjSheetInfo> getSheetContentsToMap(String filePath,boolean checkStrikeOut) throws Throwable {
HashMap<String, CsjSheetInfo> retMap = new HashMap<String, CsjSheetInfo>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
for (int i = 0; i <wb.getNumberOfSheets(); i++) {
CsjSheetInfo csjSheetInfo =getSheetContents(wb.getSheetAt(i),checkStrikeOut);
csjSheetInfo.setFilePath(filePath);
retMap.put(csjSheetInfo.getSheetNm(), csjSheetInfo);
}
fileInputStream.close();
return retMap;
}
public static CsjSheetInfo getSheetContents(Sheet sheet,
boolean checkStrikeOut) {
CsjSheetInfo retInfo = new CsjSheetInfo();
retInfo.setSheetNm(sheet.getSheetName());
Map<String, CsjCellInfo> cellMap = retInfo.getCsjCellInfoMap();
Map<Integer,CsjColInfo> csjColInfoMap = retInfo.getCsjColInfoMap();
Map<Integer,CsjRowInfo> csjRowInfoMap = retInfo.getCsjRowInfoMap();
Map<String,CsjCellInfo> csjCellPosInfoMap = retInfo.getCsjCellPosInfoMap();
Map<Integer,List<CsjCellInfo>> csjCellPosInfoRowList = retInfo.getCsjCellPosInfoRowList();
Map<Integer,List<CsjCellInfo>> csjCellPosInfoColList = retInfo.getCsjCellPosInfoColList();
try {
String str = CsjConst.EMPTY;
for (Row row : sheet) {
List<CsjCellInfo> rowCells = new ArrayList<CsjCellInfo>();
CsjRowInfo csjRowInfo = new CsjRowInfo();
csjRowInfoMap.put(row.getRowNum(), csjRowInfo);
for (Cell cell : row) {
CsjColInfo csjColInfo = null;
if (csjColInfoMap.containsKey(cell.getColumnIndex())) {
csjColInfo=csjColInfoMap.get(cell.getColumnIndex());
} else {
csjColInfo = new CsjColInfo();
csjColInfoMap.put(cell.getColumnIndex(), csjColInfo);
}
List<CsjCellInfo> colList = null;
if (csjCellPosInfoColList.containsKey(cell.getColumnIndex())) {
colList = csjCellPosInfoColList.get(cell.getColumnIndex());
} else {
colList = new ArrayList<CsjCellInfo>();
csjCellPosInfoColList.put(cell.getColumnIndex(), colList);
}
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
CsjCellInfo t =CmnPoiUtils.getCellInfo(cell);
t.setSheetNm(sheet.getSheetName());
rowCells.add(t);
cellMap.put(str, t);
csjCellPosInfoMap.put(String.valueOf(row.getRowNum()) + "_" + String.valueOf(cell.getColumnIndex()), t);
csjRowInfo.getRowMap().put(str, t);
csjColInfo.getColMap().put(str, t);
colList.add(t);
}
}
csjCellPosInfoRowList.put(row.getRowNum(), rowCells);
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
retInfo.setSheetNm(sheet.getSheetName());
return retInfo;
}
/**
* @param sheet
* @param cellInfo
* @throws Throwable
*/
public static void setCellValue(Sheet sheet, CsjCellInfo cellInfo)
throws Throwable {
if (cellInfo != null && CmnStrUtils.isNotEmpty(cellInfo.getContent()
)) {
setCellValue(sheet, cellInfo.getRowNum(), cellInfo.getCellNum(),
cellInfo.getContent());
}
}
/**
* @param string
* @param string2
* @param i
* @param j
* @param string3
* @throws Throwable
*/
public static void setCellValue(String path, String sheetNm, int row,
int col, String str) throws Throwable {
File file = new File(path);
FileInputStream fileIn = new FileInputStream(file);
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(path, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileIn);
} else {
wb = new HSSFWorkbook(fileIn);
}
setCellValue(wb.getSheet(sheetNm),row,col,str);
FileOutputStream fileOut = new FileOutputStream(path);
wb.write(fileOut);
fileOut.close();
fileIn.close();
}
/**
* @param wb
* @param s_sheetNm
* @return
*/
public static Sheet getOneSheetByNm(Workbook wb, String sheetNm) {
for (int i = wb.getNumberOfSheets()-1; i >=0 ; i--) {
if (!wb.getSheetAt(i).getSheetName().equalsIgnoreCase(sheetNm)) {
wb.removeSheetAt(i);
}
}
return wb.getSheetAt(0);
}
/**
* @param newSt
* @param row
* @param b
* @throws Throwable
*/
public static void copyRow(Sheet newSt, int rowIndex, Row row, boolean isCopyOthers) throws Throwable {
if (newSt == null || row == null) {
return;
}
try {
for (Cell cell : row) {
Cell newCell = setCellValueWithCs(newSt, rowIndex, cell.getColumnIndex(), getCellContent(cell, false), cell.getCellStyle());
newCell.setCellType(cell.getCellType());
newCell.setCellComment(cell.getCellComment());
newCell.setCellFormula(cell.getCellFormula());
}
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnRandomUtils.java
/**
*
*/
package org.mydbsee.common;
import java.util.HashSet;
import java.util.Random;
/**
* @author Think
*
*/
public class CmnRandomUtils {
public static int getRadomInt(int min,int max) {
return (int) Math.round(Math.random()*(max-min)+min);
}
/**
* 产生一个指定长度的字符串。
*/
public static String createRadomStrs(int length, Boolean isMin,
boolean number) {
char[] result = new char[length];
int m = 0;
for (; m < length;) {
int by = createRadomNum(256, true);
if (number) {
if (isMin == null) {
if ((by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
} else if (isMin) {
if (by >= 97 && by <= 122 || (by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
} else {
if ((by >= 65 && by <= 90) || (by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
}
} else {
if (isMin) {
if ((by >= 97 && by <= 122) || (by >= 65 && by <= 90)) {
result[m] = (char) by;
m++;
}
} else if (isMin) {
if (by >= 97 && by <= 122) {
result[m] = (char) by;
m++;
}
} else {
if ((by >= 65 && by <= 90)) {
result[m] = (char) by;
m++;
}
}
}
}
return String.copyValueOf(result);
}
/**
* 随机指定范围内N个不重复的数
* 最简单最基本的方法
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
*/
public static int[] randomCommon(int min, int max, int n){
if (n > (max - min + 1) || max < min) {
return null;
}
int[] result = new int[n];
int count = 0;
while(count < n) {
int num = (int) (Math.random() * (max - min)) + min;
boolean flag = true;
for (int j = 0; j < n; j++) {
if(num == result[j]){
flag = false;
break;
}
}
if(flag){
result[count] = num;
count++;
}
}
return result;
}
/**
* 随机指定范围内N个不重复的数
* 利用HashSet的特征,只能存放不同的值
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
* @param HashSet<Integer> set 随机数结果集
*/
public static void randomSet(int min, int max, int n, HashSet<Integer> set) {
if (n > (max - min + 1) || max < min) {
return;
}
for (int i = 0; i < n; i++) {
// 调用Math.random()方法
int num = (int) (Math.random() * (max - min)) + min;
set.add(num);// 将不同的数存入HashSet中
}
int setSize = set.size();
// 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小
if (setSize < n) {
randomSet(min, max, n - setSize, set);// 递归
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(getRadomInt(1,5));
}
// int[] reult1 = randomCommon(20,50,10);
// for (int i : reult1) {
// System.out.println(i);
// }
// int[] reult2 = randomArray(20,50,31);
// for (int i : reult2) {
// System.out.println(i);
// }
//
// HashSet<Integer> set = new HashSet<Integer>();
// randomSet(20,50,10,set);
// for (int j : set) {
// System.out.println(j);
// }
}
/**
* 随机指定范围内N个不重复的数
* 在初始化的无重复待选数组中随机产生一个数放入结果中,
* 将待选数组被随机到的数,用待选数组(len-1)下标对应的数替换
* 然后从len-2里随机产生下一个随机数,如此类推
* @param max 指定范围最大值
* @param min 指定范围最小值
* @param n 随机数个数
* @return int[] 随机数结果集
*/
public static int[] randomArray(int min,int max,int n){
int len = max-min+1;
if(max < min || n > len){
return null;
}
//初始化给定范围的待选数组
int[] source = new int[len];
for (int i = min; i < min+len; i++){
source[i-min] = i;
}
int[] result = new int[n];
Random rd = new Random();
int index = 0;
for (int i = 0; i < result.length; i++) {
//待选数组0到(len-2)随机一个下标
index = Math.abs(rd.nextInt() % len--);
//将随机到的数放入结果集
result[i] = source[index];
//将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换
source[index] = source[len];
}
return result;
}
/**
* 产生一个的随机整数
*/
public static int createRadomNum(int max, boolean hasZero) {
if (hasZero) {
int s = new Double(max * Math.random()).intValue();
return s;
} else {
int s = new Double(max * Math.random()).intValue();
return s == 0 ? 1 : s;
}
}
/**
* 产生一个的随机Double数
*/
public static Double createRadomDoubleNum(int max, boolean hasZero) {
if (hasZero) {
Double s = new Double(max * Math.random()).doubleValue();
return s;
} else {
Double s = new Double(max * Math.random()).doubleValue();
return s == 0 ? 1.0 : s;
}
}
}
-------C:\aa\common\CmnStrUtils.java
/**
* Copyright (c) 2012, Java CNC/CSJ for tools. All rights reserved.
*/
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import jp.co.csj.tools.core.CsjLinkedMap;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.db.core.DbInfo;
import jp.co.csj.tools.utils.db.core.TableDbItem;
import jp.co.csj.tools.utils.poi.core.CsjPosition;
import jp.co.csj.tools.utils.reg.RegConstStr;
import jp.co.csj.tools.utils.schedual.SchedualRec;
import jp.co.csj.tools.utils.schedual.SchedualRecs;
/**
* CsjStrUtils
*
* @author cuishuangjia@163.com
* @version 1.0
* @since 1.6
*/
public class CmnStrUtils {
/**
* @param text
* @return
*/
public static String convertTxtToReg(String text) {
String retStr = text.replace("\\t", "\t");
retStr = retStr.replace("\\0", "\0");
retStr = retStr.replace("\\n", "\n");
retStr = retStr.replace("\\r", "\r");
return retStr;
}
public static List<List<String>> getLstLst(SchedualRecs schedualRecs) {
List<List<String>> retLst = new ArrayList<List<String>>();
Map<String , SchedualRec> schedualRecMap = schedualRecs.getSchedualRecMap();
for (SchedualRec rec : schedualRecMap.values()) {
List<String> sLst = new ArrayList<String>();
if (rec.isChecked() && CmnStrUtils.isNotEmpty(rec.getExcelPath())&&CmnStrUtils.isNotEmpty(rec.getExcelSheetName())) {
sLst.add(rec.getExcelPath());
sLst.add(rec.getExcelSheetName());
}
retLst.add(sLst);
}
return retLst;
}
public static boolean isMatchIgnorReg(String str, String reg) {
if (isNotEmpty(str)) {
return str.toLowerCase().matches(reg.toLowerCase());
}
return false;
}
public static boolean isEndByIgnor(String str, String end) {
if (isNotEmpty(str)) {
return str.toLowerCase().endsWith(end.toLowerCase());
}
return false;
}
public static int getBitesLength(String str) {
int ret = 0;
if (isNotEmpty(str)) {
try {
ret = str.getBytes(IConstFile.ENCODE_SHIFT_JIS).length;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.debug(e.getMessage());
}
}
return ret;
}
public static String getNoNullStr(String str) {
String ret = str;
if (isEmpty(str)) {
ret = CsjConst.EMPTY;
}
return ret;
}
// 判断字符串是否为空(为NULL或者为"")
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof String) {
return obj.toString().length() == 0;
} else if (obj instanceof List) {
return ((List)obj).size()==0;
} else if (obj instanceof Map) {
return ((Map)obj).size()==0;
} else if (obj instanceof Set) {
return ((Set)obj).size()==0;
} else if (obj instanceof Object[]) {
return ((Object[])obj).length==0;
}
return false;
}
public static boolean isNotEmpty(Object obj) {
return !isEmpty(obj);
}
public static boolean isEqual(Object oldObj,Object newObj) {
boolean retVal = false;
if (oldObj==null ||newObj==null) {
return retVal;
}
if (oldObj instanceof String && newObj instanceof String) {
if (String.valueOf(oldObj).equals(newObj)) {
retVal = true;
}
}
return retVal;
}
public static boolean isNotEqual(Object oldObj,Object newObj) {
return !isEqual(oldObj,newObj);
}
public static boolean isEqualIgnorBigSmall(String oldstr, String newstr,boolean trimed) {
boolean retVal = false;
if (oldstr == null || newstr == null) {
return retVal;
}
if (trimed) {
oldstr = fromAtoBByTrim(oldstr, "", "");
newstr = fromAtoBByTrim(newstr, "", "");
}
if (CmnStrUtils.toLowOrUpStr(oldstr).equals(CmnStrUtils.toLowOrUpStr(newstr))) {
retVal = true;
}
return retVal;
}
public static boolean isUptOrIns(String sql) {
if (CmnStrUtils.isEmpty(sql)) {
return false;
}
sql = lrTrimSpace(sql);
if (sql.toLowerCase().startsWith("update")||sql.toLowerCase().startsWith("insert")||sql.toLowerCase().startsWith("delete")) {
return true;
}
return false;
}
/**
* @param paraStr
* @param string
* @param isWithBlank
*/
public static List<String> getListStrSplit(String paraStr, String splitCh,
boolean hasEmpty,boolean islrtrim) {
String[] arrStr = paraStr.split(splitCh,-1);
List<String> retStrList = new ArrayList<String>();
for (String str : arrStr) {
if (islrtrim) {
str = CmnStrUtils.lrTrimSpace(str);
}
if (hasEmpty == false && CmnStrUtils.isEmpty(str)) {
continue;
}
retStrList.add(str);
}
return retStrList;
}
public static List<CsjPosition> getPointList(String str,Set<String> set) {
List<CsjPosition> retList = new ArrayList<CsjPosition>();
str = str.toLowerCase();
for (String s : set) {
int preLenth = 0;
String strTemp = str;
while (strTemp.contains(s)) {
int startPos = strTemp.indexOf(s);
int endPos = startPos+s.length();
retList.add(new CsjPosition(preLenth+startPos, s.length()));
strTemp = strTemp.substring(endPos);
preLenth+=endPos;
}
}
return retList;
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoBByTrim(String str, String strA, String strB) {
String ret = CsjConst.EMPTY;
if (CmnStrUtils.isNotEmpty(str)) {
ret = fromAtoNearB(str, strA, strB);
ret = lrTrimSpace(ret);
}
return ret;
}
public static String hashSet2StrBy(HashSet<String> set, String ch) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(set)) {
Object[] objArr = set.toArray();
for (int i = 0; i < objArr.length; i++) {
if (i + 1 == objArr.length) {
sb.append(String.valueOf(objArr[i]));
} else {
sb.append(String.valueOf(objArr[i]));
sb.append(ch);
}
}
}
return sb.toString();
}
public static String escapeNull(String str) {
if (CmnStrUtils.isEmpty(str)) {
return "";
} else {
return str;
}
}
/**
* @param ret
* @return String
*/
public static String lrTrimSpace(String str) {
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
str = str.trim();
while (str.startsWith(CsjConst.SIGN_SPACE_1)
|| str.startsWith(CsjConst.Z_SIGN_SPACE_1)) {
str = str.substring(1, str.length());
}
while (str.endsWith(CsjConst.SIGN_SPACE_1)
|| str.endsWith(CsjConst.Z_SIGN_SPACE_1)) {
str = str.substring(0, str.length() - 1);
}
return str;
}
public static String lrTrimOnlyOne(String str, String ch,boolean isHead) {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else if (CmnStrUtils.isEmpty(ch)) {
return str;
}
if (isHead) {
if (str.startsWith(ch)) {
str = str.substring(1, str.length());
}
} else {
if (str.endsWith(ch)) {
str = str.substring(0, str.length() - 1);
}
}
return str;
}
public static String lrTrimStartEndBySet(String str, Set<String> chSet,boolean isStart) {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else if (CmnStrUtils.isEmpty(chSet)) {
return str;
}
if (isStart) {
while(true){
if (CmnStrUtils.isEmpty(str)) {
return str;
}
String begin = String.valueOf(str.charAt(0));
if (chSet.contains(begin)) {
str = str.substring(1, str.length());
} else {
break;
}
}
} else {
while(true){
if (CmnStrUtils.isEmpty(str)) {
return str;
}
String begin = String.valueOf(str.charAt(str.length() - 1));
if (chSet.contains(begin)) {
str = str.substring(0, str.length() - 1);
} else {
break;
}
}
}
return str;
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoNearB(String str, String strA, String strB) {
if (null == strA) {
strA = CsjConst.EMPTY;
}
if (null == strB) {
strB = CsjConst.EMPTY;
}
String temp = CsjConst.EMPTY;
int n = 0;
if (CsjConst.EMPTY.equals(strA)) {
if (CsjConst.EMPTY.equals(strB)) {
return str;
}
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
if (CsjConst.EMPTY.equals(strB)) {
if (!CsjConst.EMPTY.equals(strA)) {
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
return str.substring(n);
} else if (n == str.length()) {
return CsjConst.EMPTY;
}
return str;
}
return str;
}
}
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
temp = str.substring(n);
}
if (temp.contains(strB)) {
return temp.substring(0, temp.indexOf(strB));
}
return temp;
} else {
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoFarB(String str, String strA, String strB) {
if (null == strA) {
strA = CsjConst.EMPTY;
}
if (null == strB) {
strB = CsjConst.EMPTY;
}
String temp = CsjConst.EMPTY;
int n = 0;
if (CsjConst.EMPTY.equals(strA)) {
if (CsjConst.EMPTY.equals(strB)) {
return str;
}
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
if (CsjConst.EMPTY.equals(strB)) {
if (!CsjConst.EMPTY.equals(strA)) {
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
return str.substring(n);
} else if (n == str.length()) {
return CsjConst.EMPTY;
}
return str;
}
return str;
}
}
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
temp = str.substring(n);
}
if (temp.contains(strB)) {
return temp.substring(0, temp.indexOf(strB));
}
return temp;
} else {
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
}
/**
*
* @param str
* @param listSignMethod
* @param strB
* @return
*/
public static String fromAtoBByTrimWithStartList(String str,
List<String> listSignMethod, String strB) {
// TODO Auto-generated method stub
for (String string : listSignMethod) {
if (str.contains(string)) {
str = fromAtoBByTrim(str, string, strB);
}
}
return str;
}
/**
*
* @param str
* @param listSignMethod
* @param strB
* @return
*/
public static String fromAtoBByTrimWithEndList(String str,
String strA, List<String> list) {
for (String string : list) {
if (str.contains(string)) {
str = fromAtoBByTrim(str, strA, string);
}
}
return str;
}
public static String funReplace(String rStr, String rFix, String rRep) {
if (isEmpty(rStr)) {
return "";
}
int l = 0;
String gRtnStr = rStr;
do {
l = rStr.indexOf(rFix, l);
if (l == -1)
break;
gRtnStr = rStr.substring(0, l) + rRep
+ rStr.substring(l + rFix.length());
l += rRep.length();
rStr = gRtnStr;
} while (true);
return gRtnStr.substring(0, gRtnStr.length());
}
// 首字母转小写
public static String toLowerCaseFirstOne(String s) {
if (CmnStrUtils.isEmpty(s))
return "";
if (Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder())
.append(Character.toLowerCase(s.charAt(0)))
.append(s.substring(1)).toString();
}
public static String toStr(Object obj) {
if (isNotEmpty(obj)) {
return String.valueOf(obj);
}
return "";
}
// 首字母转大写
public static String toUpperCaseFirstOne(String s) {
if (CmnStrUtils.isEmpty(s)) {
return CsjConst.EMPTY;
}
if (Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder())
.append(Character.toUpperCase(s.charAt(0)))
.append(s.substring(1)).toString();
}
// public static List<HashMap<String, String>> toUpperKeyList(List<HashMap<String, String>> list, HashSet<String> setCol) {
//
// List<HashMap<String, String>> retList = new ArrayList<HashMap<String,String>>();
// for(HashMap<String, String> map : list) {
// HashMap<String, String> inMap = new HashMap<String, String>();
// for (Entry<String, String> entry : map.entrySet()) {
// String key = toLowOrUpStr(entry.getKey());
// String val = entry.getValue();
// if (setCol.contains(key)) {
// val = toLowOrUpStr(val);
// }
// inMap.put(key, val);
// }
// retList.add(inMap);
// }
//
// return retList;
// }
public static long getLongVal(String cellContents) {
long num = 0;
try {
num = (long) Double.parseDouble(cellContents);
} catch (Throwable e) {
//MyLog.logger.info(e.getMessage());
num = 0;
}
return num;
}
public static int getIntVal(String cellContents) {
return (int) getLongVal(cellContents);
}
public static double getDoubleVal(String cellContents)throws Throwable {
double num = 0;
try {
if (cellContents.endsWith("%")) {
cellContents = fromAtoBByTrim(cellContents, "", "%");
}
num = Double.parseDouble(cellContents);
} catch (Throwable e) {
throw e;
// MyLog.logger.info(e.getMessage());
// num = 0;
}
return num;
}
public static String toLowOrUpStr(Object str) {
return convertString(str).toUpperCase();
}
/**
* タイプ転換処理
*
* @param object
* Object
* @return String
*/
public static String convertString(Object object) {
String strResult = null;
if (object == null) {
strResult = "";
} else {
strResult = object.toString();
}
// 返却値を返す
return strResult;
}
public static String[] getArrFromListByRegon(List<String> strList,
boolean isHaveBlank, boolean isInFilter,String filter) {
int blankPos = isHaveBlank ? 1 : 0;
List<String> valList = new ArrayList<String>();
for (String str : strList) {
if (CmnStrUtils.isNotEmpty(filter)) {
if (isInFilter &&str.matches(filter) ) {
} else if (isInFilter==false &&str.matches(filter)==false ) {
} else {
continue;
}
}
valList.add(str);
}
strList = valList;
String[] s = new String[strList.size() + blankPos];
if (isHaveBlank) {
s[0] = "";
for (int i = 0; i < strList.size(); i++) {
s[i + 1] = strList.get(i);
}
} else {
for (int i = 0; i < strList.size(); i++) {
if (CmnStrUtils.isNotEmpty(filter)
&& strList.get(i).contains(filter)) {
continue;
}
s[i] = strList.get(i);
}
}
return s;
}
/**
* @return
*/
public static String[] getArrFromList(List<String> strList,
boolean isHaveBlank, String filter) {
int blankPos = isHaveBlank ? 1 : 0;
List<String> valList = new ArrayList<String>();
for (String str : strList) {
if (CmnStrUtils.isNotEmpty(filter) && str.contains(filter)) {
continue;
}
valList.add(str);
}
strList = valList;
String[] s = new String[strList.size() + blankPos];
if (isHaveBlank) {
s[0] = "";
for (int i = 0; i < strList.size(); i++) {
s[i + 1] = strList.get(i);
}
} else {
for (int i = 0; i < strList.size(); i++) {
if (CmnStrUtils.isNotEmpty(filter)
&& strList.get(i).contains(filter)) {
continue;
}
s[i] = strList.get(i);
}
}
return s;
}
// 字符串右补位
public static String rightFillChar(String str, char c, int length) {
while (length > str.length()) {
str += c;
}
return str;
}
public static String insertChar(String str, String ins,int pos) {
String retStr = "";
if (CmnStrUtils.isEmpty(str)) {
return retStr;
}
if (str.length()<pos) {
return str;
}
return str.substring(0, pos)+ins+str.substring(pos);
}
// 字符串左补位
public static String leftFillChar(String str, char c, int length) {
while (length > str.length()) {
str = c + str;
}
return str;
}
// 字符串左补位
public static String leftFillCharWhithByte(String str, String ch,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
// str = str.substring(0, len);
str = str.substring(str.length() - len, str.length());
}
while (length > str.getBytes("shift-jis").length) {
String oldStr = str;
str = ch + str;
if (length < str.getBytes("shift-jis").length) {
str = " " + oldStr;
}
}
} catch (Throwable e) {
// TODO Auto-generated catch block
// e.printStackTrace();
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return str;
}
// 字符串右补位
public static String rightFillCharWhithByte(String str, String ch,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
// str = str.substring(0, len);
str = str.substring(str.length() - len, str.length());
}
while (length > str.getBytes("shift-jis").length) {
String oldStr = str;
str = str + ch;
if (length < str.getBytes("shift-jis").length) {
str = oldStr + " ";
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
// 字符串右补位
public static String rPadWhithByte(String str, String ch, String chfil,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
str = str.substring(str.length() - len, str.length());
return str;
}
long filLength = length - str.getBytes("shift-jis").length;
str = str + rightFillCharWhithByte(ch, chfil, filLength);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
// 字符串左补位
public static String lPadWhithByte(String str, String ch, String chfil,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
str = str.substring(str.length() - len, str.length());
return str;
}
long filLength = length - str.getBytes("shift-jis").length;
str = str + leftFillCharWhithByte(ch, chfil, filLength);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
public static int getNumByte(long num) {
int cnt = 0;
if (num == 0) {
return 1;
}
while (num != 0) {
num = num / 10;
cnt++;
}
return cnt;
}
public static String getLastStrBySplit(String line, String splitCh) {
// TODO Auto-generated method stub
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(line)) {
} else if (!line.contains(splitCh)) {
} else {
retStr = line.substring(line.lastIndexOf(splitCh) + 1);
}
return retStr;
}
public static String trimStrByNum(String line, int num, boolean isEnd) {
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(line)) {
} else if (line.length() > num) {
if (isEnd) {
retStr = line.substring(0, line.length() - num);
} else {
retStr = line.substring(num);
}
}
return retStr;
}
public static boolean isNumeric(String str) {
if (isEmpty(str)) {
return false;
}
str = CmnStrUtils.funReplace(str, ".", "");
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
public static String getNumericByStr(String str, boolean isEnd) {
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
int a = 0;
StringBuffer tmSb = new StringBuffer(str);
StringBuffer sb = new StringBuffer();
if (isEnd) {
str = tmSb.reverse().toString();
}
int sz = str.length();
int flg = 0;
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
flg++;
} else {
if (flg != 0) {
break;
}
}
}
if (isEnd) {
sb.reverse();
}
return sb.toString();
}
public static long getAllNumericByStr(String str) {
long retVal = 0;
if (isEmpty(str)) {
return 0;
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
if (sb.length() == 0) {
retVal = 0;
} else {
retVal = Long.parseLong(sb.toString());
}
return retVal;
}
public static String getStringAllNumericByStr(String str) {
long retVal = 0;
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
if (sb.length() == 0) {
retVal = 0;
} else {
retVal = Long.parseLong(sb.toString());
}
return String.valueOf(retVal);
}
public static String getAllNumABCByStr(String str, boolean isABC123) {
if (isEmpty(str)) {
return "";
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (isABC123) {
if (String.valueOf(str.charAt(i))
.matches(RegConstStr.EN_NUM_26)) {
sb.append(str.charAt(i));
}
} else {
if (false == String.valueOf(str.charAt(i)).matches(
RegConstStr.EN_NUM_26)) {
sb.append(str.charAt(i));
}
}
}
return sb.toString();
}
/**
* @param str
* @param signDouble
* @return
*/
public static String addLRSign(String str, String signDouble) {
// TODO Auto-generated method stub
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(str)) {
retStr = CsjConst.EMPTY;
} else {
retStr = signDouble + str + signDouble;
}
return retStr;
}
/**
* @param str
* @param signDouble
* @return
*/
// TODO CSJ
public static HashMap<String, String> getSplitMap(String str,
String bSplit, String sSplit, Set<String> trimChSet,boolean isHead) {
HashMap<String, String> retMap = new HashMap<String, String>();
if (CmnStrUtils.isNotEmpty(str)) {
String[] strBArr = str.split(bSplit);
for (String strB : strBArr) {
if (strB.contains(sSplit)) {
String[] strSArr = strB.split(sSplit);
if (strSArr != null && strSArr.length >= 2) {
String key = "";
String val = "";
if (strSArr.length == 1) {
key = strSArr[0];
} else if (strSArr.length >= 2) {
key = strSArr[0];
val = strSArr[1];
}
val = CmnStrUtils.lrTrimStartEndBySet(val, trimChSet,isHead);
retMap.put(key, val);
}
}
}
}
return retMap;
}
public static InputStream String2ByteArrayInputStream(String str) {
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
return stream;
}
public static InputStream String2InputStreasm(String str) {
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
return stream;
}
public static String inputStream2String(InputStream is) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
/**
* @param oldContent
* @param paraLen
* @return
*/
public static String getStrForLength(String str, long paraLen) {
try {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else {
while (true) {
if (str.getBytes(IConstFile.ENCODE_SHIFT_JIS).length <= paraLen) {
break;
} else {
str = str.substring(0, str.length() - 1);
}
}
}
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
// TODO Auto-generated method stub
return str;
}
public static String getStrForFileNm(String str) {
String retStr = CsjConst.EMPTY;
StringBuffer sb = new StringBuffer();
if (isNotEmpty(str)) {
char[] chArr = str.toCharArray();
for (int i = 0; i < chArr.length; i++) {
String strTmp = String.valueOf(chArr[i]);
if (strTmp.matches(RegConstStr.ERROR_FILE_NM)) {
sb.append(strTmp);
}
}
retStr = sb.toString();
}
return retStr;
}
public static String[] list2StringArr(List<TableDbItem> strList) {
String[] strings = new String[strList.size()];
for (int i = 0; i < strList.size(); i++) {
strings[i] = strList.get(i).getVal();
}
return strings;
}
public static String[][] list2StringArr2(
List<CsjLinkedMap<String, TableDbItem>> list) {
String[][] data = new String[list.size()][];
for (int i = 0; i < data.length; i++) {
data[i] = list2StringArr(list.get(i).toValList(false));
}
return data;
}
/**
* // * @param data
* // * @param list
* //
*/
// public static void list2StringArr2(String[][] data,
// List<CsjLinkedMap<String, String>> list) {
// for (int i = 0; i < data.length; i++) {
// data[i] = list2StringArr(list.get(i).toValList(false));
// }
//
// }
public static List<CsjLinkedMap<String, String>> mapToCsjLinkedMap(
List<HashMap<String, String>> lstMap) {
List<CsjLinkedMap<String, String>> list = new ArrayList<CsjLinkedMap<String, String>>();
for (HashMap lstM : lstMap) {
CsjLinkedMap<String, String> cMap = new CsjLinkedMap<String, String>();
cMap.putAll(lstM);
list.add(cMap);
}
return list;
}
public static List<CsjLinkedMap<String, TableDbItem>> listMap2ListMap(
List<CsjLinkedMap<String, TableDbItem>> list) {
List<CsjLinkedMap<String, TableDbItem>> listMap = new ArrayList<CsjLinkedMap<String, TableDbItem>>();
if (list == null || list.size() == 0) {
return listMap;
}
List<String> keyLst = list.get(0).toKeyList();
int col = keyLst.size();
int row = list.size() + 1;
Object[][] objArr = new Object[row][col];
for (int i = 0; i < col; i++) {
objArr[0][i] = new TableDbItem(keyLst.get(i), keyLst.get(i),
DbInfo.TABLE_COL_TYPE_STR);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < col; j++) {
objArr[i + 1][j] = list.get(i).getValByPos(j);
}
}
for (int i = 1; i < col; i++) {
CsjLinkedMap<String, TableDbItem> map = new CsjLinkedMap<String, TableDbItem>();
for (int j = 0; j < row; j++) {
map.put(((TableDbItem) objArr[j][0]).getVal(),
((TableDbItem) objArr[j][i]));
}
listMap.add(map);
}
return listMap;
}
public static String getStringBySign(Set<String> set,String split) {
String ret = "";
for (String s : set) {
ret+=s;
}
return ret;
}
/**
* @param dbMap
* @param key
*/
public static String getMapValForConvert(HashMap<String, String> map, String key) {
if (isEmpty(map) || map.containsKey(key) == false) {
return key;
} else {
return map.get(key);
}
}
/**
* @param dbMap
* @param key
*/
public static HashSet<String> getSet(String str, String regex, boolean isWithBlank) {
HashSet<String> ret = new HashSet<String>();
if (isEmpty(str)) {
return ret;
}
for (String s : str.split(regex)) {
if (isWithBlank) {
ret.add(s);
} else {
if (isNotEmpty(s)) {
ret.add(s);
}
}
}
return ret;
}
/**
* @param createTblSqlList
*/
public static String getStrByList(List<String> strList) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(strList)) {
for(String str:strList) {
sb.append(str);
}
}
return sb.toString();
}
/**
* @param createTblSqlList
*/
public static String getStrByListWithCr(List<String> strList, boolean isHeadCr) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(strList)) {
if (isHeadCr) {
sb.append(CsjProcess.s_newLine);
}
for(String str:strList) {
sb.append(str);
}
}
return sb.toString();
}
/**
* @param retStr
* @return
*/
public static String getNumberByTrimDot0(String str) {
if (CmnStrUtils.isNotEmpty(str)) {
if (str.matches(RegConstStr.NUMBER_INTEGER)) {
str = String.valueOf(CmnStrUtils.getIntVal(str));
}
}
return str;
}
/**
* @param equalSet
* @param val
* @return
*/
public static boolean isNumInSet(Set<String> equalSet, String val) throws Throwable{
boolean retVal = false;
try {
BigDecimal bval = new BigDecimal(val);
for (String str : equalSet) {
if (bval.equals(new BigDecimal(str))) {
retVal = true;
}
}
} catch (Throwable e) {
throw e;
}
return retVal;
}
/**
* @param val
* @return
*/
public static boolean isXlsDateStr(String val) {
boolean isXlsDateStr = true;
try {
val = val.replaceAll("-", "/");
String format = CsjConst.EMPTY;
if (val.getBytes(IConstFile.ENCODE_SHIFT_JIS).length > 10) {
format = CsjConst.YYYY_MM_DD_HH_MM_SS_SLASH_24;
} else if (val.getBytes(IConstFile.ENCODE_SHIFT_JIS).length > 19) {
format = CsjConst.YYYY_MM_DD_HH_MM_SS_SLASH_24_SSS;
} else {
format = CsjConst.YYYY_MM_DD_SLASH;
}
isXlsDateStr = CmnDateUtil.checkDate(val, format);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.debug(e.getMessage());
isXlsDateStr = false;
}
return isXlsDateStr;
}
/**
* @param strDate
* @return
*/
public static String getExcelDate(String strDate) {
strDate = CmnStrUtils.fromAtoBByTrim(strDate, "", " 00:00:00.0");
return strDate;
}
public static String subStr(String str, int num) {
String retStr = "";
if (CmnStrUtils.isEmpty(str)) {
return retStr;
}
if (str.length()<num) {
return str;
} else {
return str.substring(0, num);
}
}
public static void main(String[] args) {
System.out.println(fromAtoNearB("a1ggg12", "1", "1"));
}
public static String trimLeftChar(String retVal, String trimCh) {
if (isEmpty(retVal)) {
return CsjConst.EMPTY;
}
while (retVal.startsWith(trimCh)) {
retVal = retVal.substring(1);
}
return retVal;
}
public static String getRealSql(String exeSql, String dbType) {
String presult = exeSql;
try {
String strReg = "(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/";
Pattern p = Pattern.compile(strReg);
presult = p.matcher(exeSql).replaceAll("$1");
if (DbInfo.STR_DB_TYPE_MYSQL.equals(dbType)) {
strReg = "(?ms)('(?:''|[^'])*')|#.*?$|/\\*.*?\\*/";
p = Pattern.compile(strReg);
presult = p.matcher(presult).replaceAll("$1");
}
while (presult.startsWith(CsjProcess.s_newLine)) {
presult = presult.substring(presult.indexOf(CsjProcess.s_newLine) + CsjProcess.s_newLine.length());
}
} catch (Exception e) {
CmnLog.logger.error(e.getMessage(), "");
}
return presult;
}
}
-------C:\aa\common\IConstDate.java
package org.mydbsee.common;
public interface IConstDate {
/**
* 時間について
* */
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_24 = "yyyy/MM/dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_24_SSS = "yyyy/MM/dd HH:mm:ss:SSS";
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_12 = "yyyy/MM/dd KK:mm:ss a";
public static final String YYYY_MM_DD_SLASH = "yyyy/MM/dd";
public static final String YYYY_MM_DD = "yyyyMMdd";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_24 = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_24_SSS = "yyyy-MM-dd HH:mm:ss:SSS";
public static final String HH_MM_SS_MINUS_24 = "HHmmss";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_12 = "yyyy-MM-dd KK:mm:ss a";
public static final String YY_MM_DD_HH_MM_SS_MINUS_24 = "yy/MM/dd";
public static final String YY_MM_DD_HH_MM_SS_SLASH_24 = "yy/MM/dd HH:mm:ss:SSS";
public static final String YYYY_MM_DD_MINUS = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM_SS_ALL_MINUS_24 = "yyyy-MM-dd HH-mm-ss";
public static final String YYYYMMDDHHMMSSMINUS_24 = "yyyyMMddHHmmss";
public static final String YYYYMMDDHH_MMSSMINUS_24 = "yyyyMMdd_HHmmss_SSS";
public static final String YYYYMMDDHH_HHMMSS_24 = "yyyyMMdd_HHmmss";
public static final String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
}
-------C:\aa\common\IConstFile.java
package org.mydbsee.common;
import jp.co.csj.tools.utils.common.CsjProcess;
public interface IConstFile {
// 文件后缀
public static final String DOT_INI =".ini";
public static final String DOT_INI_BAK = ".ini_bk";
//public static final String DOT_XMLBK =".xmlbk";
public static final int FILE_MAX_LEN = 200-CsjProcess.s_pj_path_length;
// 文件编码形式
public static final String ENCODE_UTF_8 = "utf-8";
public static final String ENCODE_SHIFT_JIS = "shift_jis";
public static final String ENCODE_GBK = "GBK";
public static final String ENCODE_GB2312 = "GB2312";
// ファイルパースまたはファイル
public static final int IS_PATH = 0;
public static final int IS_FILE = 1;
public static final int IS_FILES = 2;
public static final int IS_ERROR = -1;
}
-------C:\aa\common\IConstRegNum.java
/**
*
*/
package org.mydbsee.common;
/**
* @author csj
*
*/
public interface IConstRegNum {
// 非负整数(正整数 +0)
public static final String NUM_01 = "^\\d+$";
// 正整数
public static final String NUM_02 = "^[0-9]*[1-9][0-9]*$";
// 非正整数(负整数 +0)
public static final String NUM_03 = "^((-\\d+)|(0+))$";
// 负整数
public static final String NUM_04 = "^-[0-9]*[1-9][0-9]*$";
// 整数
public static final String NUM_05 = "^-?\\d+$";
// 非负浮点数(正浮点数 +0)
public static final String NUM_06 = "^\\d+(\\.\\d+)?$";
// 正浮点数
public static final String NUM_07 = "^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";
// 非正浮点数(负浮点数 +0)
public static final String NUM_08 = "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";
// 负浮点数
public static final String NUM_09 = "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$";
// 浮点数
public static final String NUM_10 = "^(-?\\d+)(\\.\\d+)?$";
// 整数或者小数
public static final String NUM_11 = "^[0-9]+\\.{0,1}[0-9]{0,2}$";
// 只能输入数字
public static final String NUM_12 = "^[0-9]*$";
// 只能输入n位的数字
public static final String NUM_13 = "^\\d{n}$";
// 只能输入至少n位的数字
public static final String NUM_14 = "^\\d{n,}$";
// 只能输入m~n位的数字
public static final String NUM_15 = "^\\d{m,n}$";
// 只能输入零和非零开头的数字
public static final String NUM_16 = "^(0|[1-9][0-9]*)$";
// 只能输入有两位小数的正实数
public static final String NUM_17 = "^[0-9]+(.[0-9]{2})?$";
// 只能输入有1~3位小数的正实数
public static final String NUM_18 = "^[0-9]+(.[0-9]{1,3})?$";
// 只能输入非零的正整数
public static final String NUM_19 = "^\\+?[1-9][0-9]*$";
public static void main(String[] args) {
System.out.println("aaaa123,(3.3,1)9dddd".replaceAll("[0-9]|\\.|\\(|\\)|,", ""));
}
}
-------C:\aa\common\IConstRegStr.java
/**
*
*/
package org.mydbsee.common;
/**
* @author csj
*
*/
public interface IConstRegStr {
public static final String EXCEL_REG_DOT = ".+xls|.+xlsx";
public static final String DATE="((^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(10|12|0?[13578])([-\\/\\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(11|0?[469])([-\\/\\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(0?2)([-\\/\\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([3579][26]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$))";
// 由26个英文字母组成的字符串
public static final String EN_26 = "^[A-Za-z]+$";
// 由26个英文字母的大写组成的字符串
public static final String EN_26_UPP = "^[A-Z]+$";
// 由26个英文字母的小写组成的字符串
public static final String EN_26_LOW = "^[a-z]+$";
// 由数字和26个英文字母组成的字符串
public static final String EN_NUM_26 = "^[A-Za-z0-9]+$";
// 由数字、26个英文字母或者下划线组成的字符串
public static final String EN_NUM_26_UNDER = "^\\w+$";
// email地址
public static final String EMAIL = "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$";//"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
//
// url
public static final String URL = "^[a-zA-z]+:// (\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";
// 验证InternetURL:"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"
public static final String INTERNET_URL = "^[a-zA-z]+:// (\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";
// 只能输入长度为3的字符
public static final String STR_3 = "^.{3}$";
// 验证用户密码(正确格式为:以字母开头,长度在6~18之间,只能包含字符、数字和下划线)
public static final String PASSWORD = "^[a-zA-Z]\\w{5,17}$";
// 删除空行(空格和制表符(tab))
public static final String BLANK_LINE = "^[ \\t]*\\n";
// 非法文件名
public static final String ERROR_FILE_NM = "^[^\\/:*?\"\"<>|]+$";
// 匹配html标签的正则表达式
public static final String HTML = "<(.*)>(.*)<\\/(.*)>|<(.*)\\/>";
// 匹配中文字符的正则表达式:
public static final String STR_CH = "[\u4e00-\u9fa5]";
// 匹配双字节字符(包括汉字在内)
public static final String STR_2 = "[^\\x00-\\xff]";
// 验证由两位数字、一个连字符再加 5 位数字组成的 ID号。
public static final String STR_001 = "/\\d{2}-\\d{5}/";
// 验证一年的12个月(正确格式为:"01"~"09"和"1"~"12")
public static final String MONTH_12 = "^(0?[1-9]|1[0-2])$";
// 验证一个月的31天:"^((0?[1-9])|((1|2)[0-9])|30|31)$"正确格式为;"01"~"09"和"1"~"31"。
public static final String DATE_31 = "^(0?[1-9]|1[0-2])$";
// 验证身份证号(15位或18位数字)
public static final String ID_CARD = "^\\d{15}|\\d{18}$";
// 验证电话号码 正确格式为:"XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。
public static final String TEL_NUMBER = "^(\\(\\d{3,4}-)|\\d{3.4}-)?\\d{7,8}$";
// 只能是jpg和bmp格式
public static final String FILE_END_JPG_BMP= "^(.*)(\\.jpg|\\.bmp)$";
// 只能是xls格式
public static final String FILE_END_XLS= "^(.*)(\\.xls)$";
// 文件夹路径
public static final String FILE_PATH = "\\[^\\]*$";
// SQL表达式
public static final String SQL_CMT_PATH = "--.*|/\\*\\\\*.+?\\\\*\\*/";//"--.*|/\\*.+?\\*/";//"--.*|/\\*.*\\*/"
public static final String SIGN_L_LINE_START = "\\*";
public static final String SIGN_R_LINE_START = "\\*/";
// IP
public static final String IP = "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
// MAC
public static final String MAC = "([0-9A-Fa-f]{2})(-[0-9A-Fa-f]{2}){5}";
// DB TYPE
public static final String DB_TYPE_REPLACE = "[0-9]|\\.|\\(|\\)|,";
public static final String DB_CONVERT_DB = "DB.*";
public static final String DB_CONVERT_TABLE = "TABLE.*";
public static final String DB_CONVERT_COL = "COL.*";
public static final String DOT_HOSI = ".*";
public static final String NUMBER_INTEGER = "^[0-9]*.[0]*$";
public static final String SIGN_T = "\t";
public static final String SIGN_R = "\r";
public static final String SIGN_N = "\n";
public static void main(String[] args) {
System.out.println("aa/*axxxxxa*/aa-abd----dad".replaceAll(SQL_CMT_PATH, ""));
}
/*
* [正则表达式]文本框输入内容控制 默认分类 2009-02-13 10:10 阅读26 评论0 字号: 大大 中中 小小
*
* 验证是否含有^%&',;=?$\"等字符:"[^%&',;=?$\x22]+"。 只能输入汉字:"^[\u4e00-\u9fa5]{0,}$"
* 验证Email地址:"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"。
* 验证InternetURL:"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"。 验证电话号码:
* "^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$"正确格式为:"XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。
*
*
*
* 匹配中文字符的正则表达式: [\u4e00-\u9fa5] 匹配双字节字符(包括汉字在内):[^\x00-\xff]
* 应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) String.prototype.len=function(){return
* this.replace(/[^\x00-\xff]/g,"aa").length;}
*
* 匹配html标签的正则表达式:<(.*)>(.*)<\/(.*)>|<(.*)\/> 匹配首尾空格的正则表达式:(^\s*)|(\s*$)
* 应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:
* String.prototype.trim = function() { return
* this.replace(/(^\s*)|(\s*$)/g, ""); } 利用正则表达式分解和转换IP地址:
* 下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的Javascript程序: function IP2V(ip) {
* re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式 if(re.test(ip)) { return
* RegExp
* .$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
* } else { throw new Error("Not a valid IP address!") } }
* 不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下: var ip="10.100.20.168"
* ip=ip.split(".")
* alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))
* 匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
* 匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
*
* 利用正则表达式限制网页表单里的文本框输入内容:
* 用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
* onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"
* 用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
* onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))"
* 用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^\d]/g,'')
* "onbeforepaste="clipboardData
* .setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"
* 用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData(
* 'text',clipboardData.getData('text').replace(/[^\d]/g,''))" <input
* onkeyup="value=value.replace(/[^\u4E00-\u9FA5\w]/g,'')" onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5\w]/g,''))"
* value="允许下划线,数字字母和汉字"> <script language="javascript"> if
* (document.layers)//触发键盘事件 document.captureEvents(Event.KEYPRESS) function
* xz(thsv,nob){ if(nob=="2"){ window.clipboardData.setData("text","")
* alert("避免非法字符输入,请勿复制字符"); return false; } if (event.keyCode!=8 &&
* event.keyCode!=16 && event.keyCode!=37 && event.keyCode!=38 &&
* event.keyCode!=39 && event.keyCode!=40){ thsvv=thsv.value;//输入的值
* thsvs=thsvv.substring(thsvv.length-1);//输入的最后一个字符
* //thsvss=thsvv.substring(0,thsvv.length-1);//去掉最后一个错误字符 if
* (!thsvs.replace(/[^\u4E00-\u9FA5\w]/g,'') ||
* event.keyCode==189){//正则除去符号和下划线 key thsv.value='请勿输入非法符号 ['+thsvs+']';
* alert('请勿输入非法符号 ['+thsvs+']'); thsv.value=""; return false; } } }
* </script> <input onkeyup="xz(this,1)" onPaste="xz(this,2)"
* value="">允许数字字母和汉字 <script language="javascript"> <!-- function
* MaxLength(field,maxlimit){ var j =
* field.value.replace(/[^\x00-\xff]/g,"**").length; //alert(j); var
* tempString=field.value; var tt=""; if(j > maxlimit){ for(var
* i=0;i<maxlimit;i++){ if(tt.replace(/[^\x00-\xff]/g,"**").length <
* maxlimit) tt = tempString.substr(0,i+1); else break; }
* if(tt.replace(/[^\x00-\xff]/g,"**").length > maxlimit)
* tt=tt.substr(0,tt.length-1); field.value = tt; }else{ ; } } </script>
* 单行文本框控制<br /> <INPUT type="text" id="Text1" name="Text1"
* onpropertychange="MaxLength(this, 5)"><br /> 多行文本框控制:<br /> <TEXTAREA
* rows="14" cols="39" id="Textarea1" name="Textarea1"
* onpropertychange="MaxLength(this, 15)"></TEXTAREA><br />
* 控制表单内容只能输入数字,中文.... <script> function test() {
* if(document.a.b.value.length>50) { alert("不能超过50个字符!");
* document.a.b.focus(); return false; } } </script> <form name=a
* onsubmit="return test()"> <textarea name="b" cols="40" wrap="VIRTUAL"
* rows="6"></textarea> <input type="submit" name="Submit" value="check">
* </form> 只能是汉字 <input
* onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"> 只能是英文字符 <script
* language=javascript> function onlyEng() {
* if(!(event.keyCode>=65&&event.keyCode<=90)) event.returnValue=false; }
* </script> <input onkeydown="onlyEng();"> <input name="coname" type="text"
* size="50" maxlength="35" class="input2"
* onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData
* ('text',clipboardData.getData('text').replace(/[^\d]/g,''))"> 只能是数字
* <script language=javascript> function onlyNum() {
* if(!((event.keyCode>=48&&
* event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
* //考虑小键盘上的数字键 event.returnValue=false; } </script> <input
* onkeydown="onlyNum();"> 只能是英文字符和数字 <input
* onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData
* ('text',clipboardData.getData('text').replace(/[^\d]/g,''))"> 验证为email格式
* <SCRIPT LANGUAGE=Javascript RUNAT=Server> function isEmail(strEmail) { if
* (
* strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*
* \.[A-Za-z0-9]+$/) != -1) return true; else alert("oh"); } </SCRIPT>
* <input type=text onblur=isEmail(this.value)> 屏蔽关键字(sex , fuck) - 已修改
* <script language="JavaScript1.2"> function test() { if((a.b.value.indexOf
* ("sex") == 0)||(a.b.value.indexOf ("fuck") == 0)){ alert("五讲四美三热爱");
* a.b.focus(); return false;} } </script> <form name=a
* onsubmit="return test()"> <input type=text name=b> <input type="submit"
* name="Submit" value="check"> </form>
*
* 限制文本框里只能输入数字 <input onkeyup="if(event.keyCode !=37 && event.keyCode !=
* 39) value=value.replace(/\D/g,
* '');"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/\D/g,''))">
* <PIXTEL_MMI_EBOOK_2005>2 </PIXTEL_MMI_EBOOK_2005>
*
* JAVA正则表达式语法(转) 正则表达式语法
*
* 正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”)。模式描述在搜索文本时要匹配的一个或多个字符串。
*
* 正则表达式示例
*
* 表达式 匹配 /^\s*$/ 匹配空行。
*
* /\d{2}-\d{5}/ 验证由两位数字、一个连字符再加 5 位数字组成的 ID 号。
*
* /<\s*(\S+)(\s[^>]*)?>[\s\S]*<\s*\/\1\s*>/ 匹配 HTML 标记。
*
* 下表包含了元字符的完整列表以及它们在正则表达式上下文中的行为:
*
*
* 字符 说明 \
* 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,“n”匹配字符“n”。“\n”匹配换行符。序列“\\”匹配“\”,“\
* (”匹配“(”。
*
* ^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与“\n”或“\r”之后的位置匹配。
*
* $ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与“\n”或“\r”之前的位置匹配。
*
*
* 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配“z”和“zoo”。* 等效于 {0,}。
*
* + 一次或多次匹配前面的字符或子表达式。例如,“zo+”与“zo”和“zoo”匹配,但与“z”不匹配。+ 等效于 {1,}。
*
* ? 零次或一次匹配前面的字符或子表达式。例如,“do(es)?”匹配“do”或“does”中的“do”。? 等效于 {0,1}。
*
* {n} n 是非负整数。正好匹配 n 次。例如,“o{2}”与“Bob”中的“o”不匹配,但与“food”中的两个“o”匹配。
*
* {n,} n 是非负整数。至少匹配 n 次。例如,“o{2,}”不匹配“Bob”中的“o”,而匹配“foooood”中的所有
* o。“o{1,}”等效于“o+”。“o{0,}”等效于“o*”。
*
* {n,m} M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,“o{1,3}”匹配“fooooood”中的头三个
* o。'o{0,1}' 等效于 'o?'。注意:您不能将空格插入逗号和数字之间。
*
* ?
* 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是“非贪心的”。“非贪心的”模式匹配搜索到的、尽可能短的字符串
* ,而默认的“贪心的”模式匹配搜索到的、尽可能长的字符串。例如,在字符串“oooo”中,“o+?”只匹配单个“o”,而“o+”匹配所有“o”。
*
* . 匹配除“\n”之外的任何单个字符。若要匹配包括“\n”在内的任意字符,请使用诸如“[\s\S]”之类的模式。
*
* (pattern) 匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果“匹配”集合中检索捕获的匹配。若要匹配括号字符
* ( ),请使用“\(”或者“\)”。
*
* (?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用“or”字符 (|)
* 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 'industry|industries' 更经济的表达式。
*
* (?=pattern) 执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern
* 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?=95|98|NT|2000)'
* 匹配“Windows 2000”中的“Windows”,但不匹配“Windows
* 3.1”中的“Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
*
* (?!pattern) 执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern
* 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?!95|98|NT|2000)'
* 匹配“Windows 3.1”中的 “Windows”,但不匹配“Windows
* 2000”中的“Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
*
* x|y 匹配 x 或 y。例如,'z|food' 匹配“z”或“food”。'(z|f)ood' 匹配“zood”或“food”。
*
* [xyz] 字符集。匹配包含的任一字符。例如,“[abc]”匹配“plain”中的“a”。
*
* [^xyz] 反向字符集。匹配未包含的任何字符。例如,“[^abc]”匹配“plain”中的“p”。
*
* [a-z] 字符范围。匹配指定范围内的任何字符。例如,“[a-z]”匹配“a”到“z”范围内的任何小写字母。
*
* [^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,“[^a-z]”匹配任何不在“a”到“z”范围内的任何字符。
*
* \b 匹配一个字边界,即字与空格间的位置。例如,“er\b”匹配“never”中的“er”,但不匹配“verb”中的“er”。
*
* \B 非字边界匹配。“er\B”匹配“verb”中的“er”,但不匹配“never”中的“er”。
*
* \cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定
* c 就是“c”字符本身。
*
* \d 数字字符匹配。等效于 [0-9]。
*
* \D 非数字字符匹配。等效于 [^0-9]。
*
* \f 换页符匹配。等效于 \x0c 和 \cL。
*
* \n 换行符匹配。等效于 \x0a 和 \cJ。
*
* \r 匹配一个回车符。等效于 \x0d 和 \cM。
*
* \s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。
*
* \S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。
*
* \t 制表符匹配。与 \x09 和 \cI 等效。
*
* \v 垂直制表符匹配。与 \x0b 和 \cK 等效。
*
* \w 匹配任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。
*
* \W 与任何非单词字符匹配。与“[^A-Za-z0-9_]”等效。
*
* \xn 匹配 n,此处的 n
* 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,“\x41”匹配“A”。“\x041”与“\x04”&“
* 1”等效。允许在正则表达式中使用 ASCII 代码。
*
* \num 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,“(.)\1”匹配两个连续的相同字符。
*
* \n 标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数
* (0-7),那么 n 是八进制转义码。
*
* \nm 标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n
* 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字
* (0-7)。
*
* \nml 当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml。
匹配中文字符的正则表达式: [u4e00-u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^x00-xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:ns*r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:< (S*?)[^>]*>.*?|< .*? />
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^s*|s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:d{3}-d{8}|d{4}-d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]d{5}(?!d)
评注:中国邮政编码为6位数字
匹配身份证:d{15}|d{18}
评注:中国的身份证为15位或18位
匹配ip地址:d+.d+.d+.d+
评注:提取ip地址时有用
匹配特定数字:
^[1-9]d*$ //匹配正整数
^-[1-9]d*$ //匹配负整数
^-?[1-9]d*$ //匹配整数
^[1-9]d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]d*.d*|0.d*[1-9]d*$ //匹配正浮点数
^-([1-9]d*.d*|0.d*[1-9]d*)$ //匹配负浮点数
^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$ //匹配浮点数
^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$ //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$ //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
^w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
在使用RegularExpressionValidator验证控件时的验证功能及其验证表达式介绍如下:
只能输入数字:“^[0-9]*$”
只能输入n位的数字:“^d{n}$”
只能输入至少n位数字:“^d{n,}$”
只能输入m-n位的数字:“^d{m,n}$”
只能输入零和非零开头的数字:“^(0|[1-9][0-9]*)$”
只能输入有两位小数的正实数:“^[0-9]+(.[0-9]{2})?$”
只能输入有1-3位小数的正实数:“^[0-9]+(.[0-9]{1,3})?$”
只能输入非零的正整数:“^+?[1-9][0-9]*$”
只能输入非零的负整数:“^-[1-9][0-9]*$”
只能输入长度为3的字符:“^.{3}$”
只能输入由26个英文字母组成的字符串:“^[A-Za-z]+$”
只能输入由26个大写英文字母组成的字符串:“^[A-Z]+$”
只能输入由26个小写英文字母组成的字符串:“^[a-z]+$”
只能输入由数字和26个英文字母组成的字符串:“^[A-Za-z0-9]+$”
只能输入由数字、26个英文字母或者下划线组成的字符串:“^w+$”
验证用户密码:“^[a-zA-Z]w{5,17}$”正确格式为:以字母开头,长度在6-18之间,
只能包含字符、数字和下划线。
验证是否含有^%&’,;=?$”等字符:“[^%&’,;=?$x22]+”
只能输入汉字:“^[u4e00-u9fa5],{0,}$”
验证Email地址:“^w+[-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$”
验证InternetURL:“^http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$”
验证电话号码:“^((d{3,4})|d{3,4}-)?d{7,8}$”
正确格式为:“XXXX-XXXXXXX”,“XXXX-XXXXXXXX”,“XXX-XXXXXXX”,
“XXX-XXXXXXXX”,“XXXXXXX”,“XXXXXXXX”。
验证身份证号(15位或18位数字):“^d{15}|d{}18$”
验证一年的12个月:“^(0?[1-9]|1[0-2])$”正确格式为:“01”-“09”和“1”“12”
验证一个月的31天:“^((0?[1-9])|((1|2)[0-9])|30|31)$”
正确格式为:“01”“09”和“1”“31”。
匹配中文字符的正则表达式: [u4e00-u9fa5]
匹配双字节字符(包括汉字在内):[^x00-xff]
匹配空行的正则表达式:n[s| ]*r
匹配HTML标记的正则表达式:/< (.*)>.*|< (.*) />/
匹配首尾空格的正则表达式:(^s*)|(s*$)
匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
匹配网址URL的正则表达式:http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
(1)应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
String.prototype.len=function(){return this.replace([^x00-xff]/g,”aa”).length;}
(2)应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现
String.prototype.trim = function()
{
return this.replace(/(^s*)|(s*$)/g, “”);
}
(3)应用:利用正则表达式分解和转换IP地址
function IP2V(ip) //IP地址转换成对应数值
{
re=/(d+).(d+).(d+).(d+)/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error(”Not a valid IP address!”)
}
}
*/
}
-------C:\aa\exe\AutoSql.java
package org.mydbsee.common.exe;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.mydbsee.common.CmnDateUtil;
import org.mydbsee.common.CmnFileUtils;
import org.mydbsee.common.CmnLog5j;
import org.mydbsee.common.CmnStrUtils;
import org.mydbsee.common.IConstDate;
import org.mydbsee.common.IConstFile;
public class AutoSql {
public static Map<String,String> commentMap = new HashMap<String,String>();
public static Map<String,String> optypeMap = new HashMap<String,String>();
public static void run() {
try {
String autoTime = CmnDateUtil.getCurrentDateString(IConstDate.YYYYMMDDHH_MMSSMINUS_24);
CmnLog5j.initLog5j(autoTime + "_log.txt",IConstFile.ENCODE_UTF_8);
readFileProperty(commentMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\comment.txt");
readFileProperty(optypeMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\optype.txt");
List<File> flst = CmnFileUtils.getFilesList("C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\FileRecv\\src_1103\\src\\jp\\co\\zc\\card\\ssm", true);
for (File f : flst) {
if (!f.getName().toLowerCase().endsWith(".xml")) {
continue;
}
String directory= "C:\\"+autoTime+ "\\"+ CmnStrUtils.fromAtoNearB(f.getAbsolutePath(), "C:\\", f.getName());
String pjName = CmnStrUtils.fromAtoNearB(f.getName(), "C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\", "\\");
String fileNm = CmnStrUtils.fromAtoNearB(f.getName(), "", ".xml");
List<String> strLst = CmnFileUtils.getFileContent(f, IConstFile.ENCODE_UTF_8);
List<OperateInfo> operateInfoLst = new ArrayList<OperateInfo>();
for (int i=0; i < strLst.size(); i++) {
for (Entry<String,String> entryOpType : optypeMap.entrySet()) {
if (strLst.get(i).toLowerCase().contains(entryOpType.getKey().toLowerCase())) {
OperateInfo operateInfo = new OperateInfo();
operateInfoLst.add(operateInfo);
operateInfo.operateType = entryOpType.getKey().toLowerCase();
operateInfo.id = CmnStrUtils.fromAtoNearB(CmnStrUtils.fromAtoFarB(strLst.get(i), "id", ""), "\"", "\"");
while(!strLst.get(++i).toLowerCase().contains(entryOpType.getValue().toLowerCase())) {
operateInfo.strList.add(strLst.get(i));
}
for (int j = 0; j < operateInfo.strList.size(); j++) {
String line = operateInfo.strList.get(j);
line = getParaLine(line,operateInfo);
line = getCommentLine(line);
operateInfo.strList.set(j, line);
}
writeFile(directory,pjName,fileNm,operateInfo);
}
}
}
}
} catch (Throwable e) {
CmnLog5j.writeLine(e.getStackTrace().toString());
System.out.println(e.getMessage());
} finally {
try {
CmnLog5j.closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
run();
}
private static void writeFile(String path,String pjName, String fileNm, OperateInfo operateInfo) throws Throwable {
File file = new File(path);
file.mkdirs();
BufferedWriter bwOracle = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_O.txt"), IConstFile.ENCODE_UTF_8));
BufferedWriter bwMysql = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_M.txt"), IConstFile.ENCODE_UTF_8));
writeSql(operateInfo, bwOracle,true);
writeSql(operateInfo, bwMysql,false);
}
private static void writeSql(OperateInfo operateInfo, BufferedWriter bw, boolean isOracle) throws Throwable {
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "trasaction");
}
for(Entry<String,String> entry : operateInfo.defineMap.entrySet()) {
String param = entry.getKey();
String type = entry.getValue();
if (isOracle) {
CmnLog5j.writeLineWithConsole(bw, "oaaa" + param + "obbb" + "/*" + type + "*/");
} else {
CmnLog5j.writeLineWithConsole(bw, "maaa" + param + "mbbb" + "/*" + type + "*/");
}
}
for(String str : operateInfo.strList) {
if (isOracle) {
str = str.replace("$$$", "OOOO");
}else {
str = str.replace("$$$", "MMMM");
}
CmnLog5j.writeLineWithConsole(bw, str);
}
CmnLog5j.writeLineWithConsole(bw, ";");
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "rollback;");
}
CmnLog5j.close(bw);
}
private static String getCommentLine(String line) {
String str = line;
System.out.println(str);
for (Entry<String, String> entry : commentMap.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
List<String> list = new ArrayList<String>();
while (str.indexOf(key) >= 0) {
System.out.println(str);
String str1 = str.substring(0, str.indexOf(key));
list.add(str1 + "/*");
if (CmnStrUtils.isEmpty(val)) {
list.add(str.substring(str.indexOf(key)) + "*/");
str = str.substring(str.indexOf(key)+key.length());
} else {
list.add(str.substring(str.indexOf(key), str.indexOf(val) + 1) + "*/");
str = str.substring(str.indexOf(val) + 1);
}
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
str = sb.toString();
}
return str;
}
private static String getParaLine(String line, OperateInfo operateInfo) {
if (!line.contains("#{")) {
return line;
}
String str = line;
List<String> list = new ArrayList<String>();
while(str.indexOf("#{")>=0) {
String str1 = str.substring(0, str.indexOf("#{"));
list.add(str1);
String paraName = CmnStrUtils.fromAtoNearB(str, "#{", ",");
list.add("$$$"+paraName);
String paraType = "XXXXXX";
if (CmnStrUtils.fromAtoNearB(str, "#{", "}").contains("jdbcType=")) {
paraType = CmnStrUtils.fromAtoNearB(str, "jdbcType=", "}");
}
operateInfo.defineMap.put(paraName, paraType);
System.out.println(str);
list.add(str.substring(str.indexOf("#{"), str.indexOf("}")+1));
str = str.substring(str.indexOf("}")+1);
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
return sb.toString();
}
private static void readFileProperty(Map<String,String> map,String filePath) throws Throwable {
List<String> strLst = CmnFileUtils.getFileContent(filePath, IConstFile.ENCODE_UTF_8);
for (String s: strLst) {
String sArr[] = s.split(",");
if (sArr.length==1) {
map.put(sArr[0], null);
} else if (sArr.length==2) {
map.put(sArr[0], sArr[1]);
}
}
}
}
class OperateInfo {
public Map<String,String> defineMap = new LinkedHashMap<String,String>();
public String operateType;
public String id;
public List<String> strList = new ArrayList<>();
}
//<if,>
//#{,}
//<when,>
//<foreach,>
//</foreach>
//<trim,>
//</trim>
//</if>
//<otherwise,>
//</otherwise>
//</when>
//<choose,>
//</choose>
//<set,>
//</set>
//<where,>
//</where>
//<update,</update>
//<select,</select>
//<insert,</insert>
//<delete,</delete>
-------C:\aa\exe\comment.txt
<if,>
#{,}
<when,>
<foreach,>
</foreach>
<trim,>
</trim>
</if>
<otherwise,>
</otherwise>
</when>
<choose,>
</choose>
<set,>
</set>
<where,>
</where>
-------C:\aa\exe\optype.txt
<update,</update>
<select,</select>
<insert,</insert>
<delete,</delete>
-------C:\aa\common\exe\AutoSql.java
package org.mydbsee.common.exe;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.mydbsee.common.CmnDateUtil;
import org.mydbsee.common.CmnFileUtils;
import org.mydbsee.common.CmnLog5j;
import org.mydbsee.common.CmnStrUtils;
import org.mydbsee.common.IConstDate;
import org.mydbsee.common.IConstFile;
public class AutoSql {
public static Map<String,String> commentMap = new HashMap<String,String>();
public static Map<String,String> optypeMap = new HashMap<String,String>();
public static void run() {
try {
String autoTime = CmnDateUtil.getCurrentDateString(IConstDate.YYYYMMDDHH_MMSSMINUS_24);
CmnLog5j.initLog5j(autoTime + "_log.txt",IConstFile.ENCODE_UTF_8);
readFileProperty(commentMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\comment.txt");
readFileProperty(optypeMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\optype.txt");
List<File> flst = CmnFileUtils.getFilesList("C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\FileRecv\\src_1103\\src\\jp\\co\\zc\\card\\ssm", true);
for (File f : flst) {
if (!f.getName().toLowerCase().endsWith(".xml")) {
continue;
}
String directory= "C:\\"+autoTime+ "\\"+ CmnStrUtils.fromAtoNearB(f.getAbsolutePath(), "C:\\", f.getName());
String pjName = CmnStrUtils.fromAtoNearB(f.getName(), "C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\", "\\");
String fileNm = CmnStrUtils.fromAtoNearB(f.getName(), "", ".xml");
List<String> strLst = CmnFileUtils.getFileContent(f, IConstFile.ENCODE_UTF_8);
List<OperateInfo> operateInfoLst = new ArrayList<OperateInfo>();
for (int i=0; i < strLst.size(); i++) {
for (Entry<String,String> entryOpType : optypeMap.entrySet()) {
if (strLst.get(i).toLowerCase().contains(entryOpType.getKey().toLowerCase())) {
OperateInfo operateInfo = new OperateInfo();
operateInfoLst.add(operateInfo);
operateInfo.operateType = entryOpType.getKey().toLowerCase();
operateInfo.id = CmnStrUtils.fromAtoNearB(CmnStrUtils.fromAtoFarB(strLst.get(i), "id", ""), "\"", "\"");
while(!strLst.get(++i).toLowerCase().contains(entryOpType.getValue().toLowerCase())) {
operateInfo.strList.add(strLst.get(i));
}
for (int j = 0; j < operateInfo.strList.size(); j++) {
String line = operateInfo.strList.get(j);
line = getParaLine(line,operateInfo);
line = getCommentLine(line);
operateInfo.strList.set(j, line);
}
writeFile(directory,pjName,fileNm,operateInfo);
}
}
}
}
} catch (Throwable e) {
CmnLog5j.writeLine(e.getStackTrace().toString());
System.out.println(e.getMessage());
} finally {
try {
CmnLog5j.closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
run();
}
private static void writeFile(String path,String pjName, String fileNm, OperateInfo operateInfo) throws Throwable {
File file = new File(path);
file.mkdirs();
BufferedWriter bwOracle = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_O.txt"), IConstFile.ENCODE_UTF_8));
BufferedWriter bwMysql = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_M.txt"), IConstFile.ENCODE_UTF_8));
writeSql(operateInfo, bwOracle,true);
writeSql(operateInfo, bwMysql,false);
}
private static void writeSql(OperateInfo operateInfo, BufferedWriter bw, boolean isOracle) throws Throwable {
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "trasaction");
}
for(Entry<String,String> entry : operateInfo.defineMap.entrySet()) {
String param = entry.getKey();
String type = entry.getValue();
if (isOracle) {
CmnLog5j.writeLineWithConsole(bw, "oaaa" + param + "obbb" + "/*" + type + "*/");
} else {
CmnLog5j.writeLineWithConsole(bw, "maaa" + param + "mbbb" + "/*" + type + "*/");
}
}
for(String str : operateInfo.strList) {
if (isOracle) {
str = str.replace("$$$", "OOOO");
}else {
str = str.replace("$$$", "MMMM");
}
CmnLog5j.writeLineWithConsole(bw, str);
}
CmnLog5j.writeLineWithConsole(bw, ";");
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "rollback;");
}
CmnLog5j.close(bw);
}
private static String getCommentLine(String line) {
String str = line;
System.out.println(str);
for (Entry<String, String> entry : commentMap.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
List<String> list = new ArrayList<String>();
while (str.indexOf(key) >= 0) {
System.out.println(str);
String str1 = str.substring(0, str.indexOf(key));
list.add(str1 + "/*");
if (CmnStrUtils.isEmpty(val)) {
list.add(str.substring(str.indexOf(key)) + "*/");
str = str.substring(str.indexOf(key)+key.length());
} else {
list.add(str.substring(str.indexOf(key), str.indexOf(val) + 1) + "*/");
str = str.substring(str.indexOf(val) + 1);
}
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
str = sb.toString();
}
return str;
}
private static String getParaLine(String line, OperateInfo operateInfo) {
if (!line.contains("#{")) {
return line;
}
String str = line;
List<String> list = new ArrayList<String>();
while(str.indexOf("#{")>=0) {
String str1 = str.substring(0, str.indexOf("#{"));
list.add(str1);
String paraName = CmnStrUtils.fromAtoNearB(str, "#{", ",");
list.add("$$$"+paraName);
String paraType = "XXXXXX";
if (CmnStrUtils.fromAtoNearB(str, "#{", "}").contains("jdbcType=")) {
paraType = CmnStrUtils.fromAtoNearB(str, "jdbcType=", "}");
}
operateInfo.defineMap.put(paraName, paraType);
System.out.println(str);
list.add(str.substring(str.indexOf("#{"), str.indexOf("}")+1));
str = str.substring(str.indexOf("}")+1);
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
return sb.toString();
}
private static void readFileProperty(Map<String,String> map,String filePath) throws Throwable {
List<String> strLst = CmnFileUtils.getFileContent(filePath, IConstFile.ENCODE_UTF_8);
for (String s: strLst) {
String sArr[] = s.split(",");
if (sArr.length==1) {
map.put(sArr[0], null);
} else if (sArr.length==2) {
map.put(sArr[0], sArr[1]);
}
}
}
}
class OperateInfo {
public Map<String,String> defineMap = new LinkedHashMap<String,String>();
public String operateType;
public String id;
public List<String> strList = new ArrayList<>();
}
//<if,>
//#{,}
//<when,>
//<foreach,>
//</foreach>
//<trim,>
//</trim>
//</if>
//<otherwise,>
//</otherwise>
//</when>
//<choose,>
//</choose>
//<set,>
//</set>
//<where,>
//</where>
//<update,</update>
//<select,</select>
//<insert,</insert>
//<delete,</delete>
-------C:\aa\common\exe\comment.txt
<if,>
#{,}
<when,>
<foreach,>
</foreach>
<trim,>
</trim>
</if>
<otherwise,>
</otherwise>
</when>
<choose,>
</choose>
<set,>
</set>
<where,>
</where>
-------C:\aa\common\exe\optype.txt
<update,</update>
<select,</select>
<insert,</insert>
<delete,</delete>
/**
*
*/
package org.mydbsee.common;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
/**
* @author Think
*
*/
public class CmnDateParse {
private SimpleDateFormat fmt = null;
private ParsePosition pos = null;
/**
* @return the fmt
*/
public SimpleDateFormat getFmt() {
return fmt;
}
/**
* @param fmt the fmt to set
*/
public void setFmt(SimpleDateFormat fmt) {
this.fmt = fmt;
}
/**
* @return the pos
*/
public ParsePosition getPos() {
return pos;
}
/**
* @param pos the pos to set
*/
public void setPos(ParsePosition pos) {
this.pos = pos;
}
}
-------C:\aa\common\CmnDateUtil.java
/*
* @(#) 所有版权归聚灵工作室所有.
*
* $Id$
*
* ===================================
* Electric Operation Maintenance System(EOMS)
*
* Copyright (c) 2006 by INSPUR LG, Inc.
* All rights reserved.
*/
package org.mydbsee.common;
import java.io.Serializable;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
/**
* 日期操作工具类,主要实现了日期的常用操作。
* <p>
* 在工具类中经常使用到工具类的格式化描述,这个主要是一个日期的操作类,所以日志格式主要使用 SimpleDateFormat的定义格式.
* <p>
* 格式的意义如下: 日期和时间模式 <br>
* 日期和时间格式由日期和时间模式字符串指定。在日期和时间模式字符串中,未加引号的字母 'A' 到 'Z' 和 'a' 到 'z'
* 被解释为模式字母,用来表示日期或时间字符串元素。文本可以使用单引号 (') 引起来,以免进行解释。"''"
* 表示单引号。所有其他字符均不解释;只是在格式化时将它们简单复制到输出字符串,或者在分析时与输入字符串进行匹配。
* <p>
* 定义了以下模式字母(所有其他字符 'A' 到 'Z' 和 'a' 到 'z' 都被保留): <br>
* <table>
* <tr>
* <td>字母</td>
* <td>日期或时间元素</td>
* <td>表示</td>
* <td>示例</td>
* <td>
* </tr>
* <tr>
* <td>G</td>
* <td>Era</td>
* <td>标志符</td>
* <td>Text</td>
* <td>AD</td>
* <td>
* </tr>
* <tr>
* <td>y</td>
* <td>年</td>
* <td>Year</td>
* <td>1996;</td>
* <td>96</td>
* <td>
* </tr>
* <tr>
* <td>M</td>
* <td>年中的月份</td>
* <td>Month</td>
* <td>July;</td>
* <td>Jul;</td>
* <td>07
* </tr>
* <tr>
* <td>w</td>
* <td>年中的周数</td>
* <td>Number</td>
* <td>27</td>
* <td>
* </tr>
* <tr>
* <td>W</td>
* <td>月份中的周数</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>D</td>
* <td>年中的天数</td>
* <td>Number</td>
* <td>189</td>
* <td>
* </tr>
* <tr>
* <td>d</td>
* <td>月份中的天数</td>
* <td>Number</td>
* <td>10</td>
* <td>
* </tr>
* <tr>
* <td>F</td>
* <td>月份中的星期</td>
* <td>Number</td>
* <td>2</td>
* <td>
* </tr>
* <tr>
* <td>E</td>
* <td>星期中的天数</td>
* <td>Text</td>
* <td>Tuesday;</td>
* <td>Tue
* </tr>
* <tr>
* <td>a</td>
* <td>Am/pm</td>
* <td>标记</td>
* <td>Text</td>
* <td>PM</td>
* <td>
* </tr>
* <tr>
* <td>H</td>
* <td>一天中的小时数(0-23)</td>
* <td>Number</td>
* <td>0
* </tr>
* <tr>
* <td>k</td>
* <td>一天中的小时数(1-24)</td>
* <td>Number</td>
* <td>24</td>
* <td>
* </tr>
* <tr>
* <td>K</td>
* <td>am/pm</td>
* <td>中的小时数(0-11)</td>
* <td>Number</td>
* <td>0</td>
* <td>
* </tr>
* <tr>
* <td>h</td>
* <td>am/pm</td>
* <td>中的小时数(1-12)</td>
* <td>Number</td>
* <td>12</td>
* <td>
* </tr>
* <tr>
* <td>m</td>
* <td>小时中的分钟数</td>
* <td>Number</td>
* <td>30</td>
* <td>
* </tr>
* <tr>
* <td>s</td>
* <td>分钟中的秒数</td>
* <td>Number</td>
* <td>55</td>
* <td>
* </tr>
* <tr>
* <td>S</td>
* <td>毫秒数</td>
* <td>Number</td>
* <td>978</td>
* <td>
* </tr>
* <tr>
* <td>z</td>
* <td>时区</td>
* <td>General</td>
* <td>time</td>
* <td>zone</td>
* <td>Pacific</td>
* <td>Standard</td>
* <td>Time;</td>
* <td>PST;</td>
* <td>GMT-08:00
* </tr>
* <tr>
* <td>Z</td>
* <td>时区</td>
* <td>RFC</td>
* <td>822</td>
* <td>time</td>
* <td>zone</td>
* <td>-0800</td>
* <td>
* </tr>
* </table>
*
* 模式字母通常是重复的,其数量确定其精确表示:
*
*/
public final class CmnDateUtil implements Serializable {
private static final long serialVersionUID = -3098985139095632110L;
private static Map<String,CmnDateParse> dateParseMap = new HashMap<String, CmnDateParse>();
private CmnDateUtil() {
}
public static void main(String[] args) {
// System.out.println(getYearByDate(new Date()));
System.out.println(getYMDhms6(new Date()));
}
public static List<Integer> getYMDhms6(Date date) {
List<Integer> lst = new ArrayList<Integer>();
Calendar cal=Calendar.getInstance();
cal.setTime(date);
lst.add(cal.get(Calendar.YEAR));
lst.add(cal.get(Calendar.MONTH));
lst.add(cal.get(Calendar.DAY_OF_MONTH)+1);
lst.add(cal.get(Calendar.HOUR_OF_DAY));
lst.add(cal.get(Calendar.MINUTE));
lst.add(cal.get(Calendar.SECOND));
return lst;
}
public static String getYearByDate(Date date) {
return String.valueOf(getYMDhms6(date).get(0));
}
/**
* 格式化日期显示格式
*
* @param sdate
* 原始日期格式 s - 表示 "yyyy-mm-dd" 形式的日期的 String 对象
* @param format
* 格式化后日期格式
* @return 格式化后的日期显示
*/
public static String dateFormat(String sdate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
java.sql.Date date = java.sql.Date.valueOf(sdate);
String dateString = formatter.format(date);
return dateString;
}
/**
* 求两个日期相差天数
*
* @param sd
* 起始日期,格式yyyy-MM-dd
* @param ed
* 终止日期,格式yyyy-MM-dd
* @return 两个日期相差天数
*/
public static long getIntervalDays(String sd, String ed) {
return ((java.sql.Date.valueOf(ed)).getTime() - (java.sql.Date.valueOf(sd)).getTime()) / (3600 * 24 * 1000);
}
/**
* 起始年月yyyy-MM与终止月yyyy-MM之间跨度的月数。
*
* @param beginMonth
* 格式为yyyy-MM
* @param endMonth
* 格式为yyyy-MM
* @return 整数。
*/
public static int getInterval(String beginMonth, String endMonth) {
int intBeginYear = Integer.parseInt(beginMonth.substring(0, 4));
int intBeginMonth = Integer.parseInt(beginMonth.substring(beginMonth.indexOf("-") + 1));
int intEndYear = Integer.parseInt(endMonth.substring(0, 4));
int intEndMonth = Integer.parseInt(endMonth.substring(endMonth.indexOf("-") + 1));
return ((intEndYear - intBeginYear) * 12) + (intEndMonth - intBeginMonth) + 1;
}
public static boolean checkDate(String sDate, String dateFormat)throws Throwable {
Date date = getDate(sDate, dateFormat);
if (date == null) {
return false;
}
String str = getFormatDateTime(date, dateFormat);
if (!CmnStrUtils.isEqual(str, sDate)) {
return false;
}
return true;
}
/**
* 根据给定的分析位置开始分析日期/时间字符串。例如,时间文本 "07/10/96 4:5 PM, PDT" 会分析成等同于
* Date(837039928046) 的 Date。
*
* @param sDate
* @param dateFormat
* @return
* @throws Throwable
*/
public static Date getDate(String sDate, String dateFormat) throws Throwable{
CmnDateParse csjDateParse = dateParseMap.get(dateFormat);
SimpleDateFormat fmt = null;
ParsePosition pos = null;
if (csjDateParse == null) {
fmt = new SimpleDateFormat(dateFormat);
pos = new ParsePosition(0);
dateParseMap.put(sDate, csjDateParse);
} else {
fmt = csjDateParse.getFmt();
pos = csjDateParse.getPos();
}
return fmt.parse(sDate, pos);
}
/**
* 取得当前日期的年份,以yyyy格式返回.
*
* @return 当年 yyyy
*/
public static String getCurrentYear()throws Throwable {
return getFormatCurrentTime("yyyy");
}
/**
* 自动返回上一年。例如当前年份是2007年,那么就自动返回2006
*
* @return 返回结果的格式为 yyyy
*/
public static String getBeforeYear()throws Throwable {
String currentYear = getFormatCurrentTime("yyyy");
int beforeYear = Integer.parseInt(currentYear) - 1;
return "" + beforeYear;
}
/**
* 取得当前日期的月份,以MM格式返回.
*
* @return 当前月份 MM
*/
public static String getCurrentMonth()throws Throwable {
return getFormatCurrentTime("MM");
}
/**
* 取得当前日期的天数,以格式"dd"返回.
*
* @return 当前月中的某天dd
*/
public static String getCurrentDay()throws Throwable {
return getFormatCurrentTime("dd");
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentDate() throws Throwable{
return getFormatDateTime(new Date(), "yyyy-MM-dd");
}
/**
* 返回当前指定的时间戳。格式为yyyy-MM-dd HH:mm:ss
*
* @return 格式为yyyy-MM-dd HH:mm:ss,总共19位。
*/
public static String getCurrentDateTime() throws Throwable{
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatDate(Date date)throws Throwable {
return getFormatDateTime(date, "yyyy-MM-dd");
}
/**
* 根据制定的格式,返回日期字符串。例如2007-05-05
*
* @param format
* "yyyy-MM-dd" 或者 "yyyy/MM/dd",当然也可以是别的形式。
* @return 指定格式的日期字符串。
*/
public static String getFormatDate(String format)throws Throwable {
return getFormatDateTime(new Date(), format);
}
/**
* 返回当前时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getCurrentTime()throws Throwable {
return getFormatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回给定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @param date
* 日期
* @return String 指定格式的日期字符串.
*/
public static String getFormatTime(Date date)throws Throwable {
return getFormatDateTime(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 根据给定的格式,返回时间字符串。
* <p>
* 格式参照类描绘中说明.和方法getFormatDate是一样的。
*
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatCurrentTime(String format)throws Throwable {
return getFormatDateTime(new Date(), format);
}
/**
* 根据给定的格式与时间(Date类型的),返回时间字符串。最为通用。<br>
*
* @param date
* 指定的日期
* @param format
* 日期格式字符串
* @return String 指定格式的日期字符串.
*/
public static String getFormatDateTime(Date date, String format) throws Throwable{
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}
/**
* 取得指定年月日的日期对象.
*
* @param year
* 年
* @param month
* 月注意是从1到12
* @param day
* 日
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(int year, int month, int day) {
Calendar c = new GregorianCalendar();
c.set(year, month - 1, day);
return c.getTime();
}
/**
* 获取指定日期的下一天。
*
* @param date
* yyyy/MM/dd
* @return yyyy/MM/dd
*/
public static String getDateTomorrow(String date)throws Throwable {
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, 1);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 获取与指定日期相差指定天数的日期。
*
* @param date
* yyyy/MM/dd
* @param offset
* 正整数
* @return yyyy/MM/dd
*/
public static String getDateOffset(String date, int offset)throws Throwable {
// Date tempDate = getDateObj(date, "[/]");
Date tempDate = null;
if (date.indexOf("/") > 0)
tempDate = getDateObj(date, "[/]");
if (date.indexOf("-") > 0)
tempDate = getDateObj(date, "[-]");
tempDate = getDateAdd(tempDate, offset);
return getFormatDateTime(tempDate, "yyyy/MM/dd");
}
/**
* 取得指定分隔符分割的年月日的日期对象.
*
* @param argsDate
* 格式为"yyyy-MM-dd"
* @param split
* 时间格式的间隔符,例如“-”,“/”,要和时间一致起来。
* @return 一个java.util.Date()类型的对象
*/
public static Date getDateObj(String argsDate, String split) {
String[] temp = argsDate.split(split);
int year = new Integer(temp[0]).intValue();
int month = new Integer(temp[1]).intValue();
int day = new Integer(temp[2]).intValue();
return getDateObj(year, month, day);
}
/**
* 取得给定字符串描述的日期对象,描述模式采用pattern指定的格式.
*
* @param dateStr
* 日期描述 从给定字符串的开始分析文本,以生成一个日期。该方法不使用给定字符串的整个文本。 有关日期分析的更多信息,请参阅
* parse(String, ParsePosition) 方法。一个 String,应从其开始处进行分析
*
* @param pattern
* 日期模式
* @return 给定字符串描述的日期对象。
*/
public static Date getDateFromString(String dateStr, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date resDate = null;
try {
resDate = sdf.parse(dateStr);
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return resDate;
}
/**
* 取得当前Date对象.
*
* @return Date 当前Date对象.
*/
public static Date getDateObj() {
Calendar c = new GregorianCalendar();
return c.getTime();
}
/**
*
* @return 当前月份有多少天;
*/
public static int getDaysOfCurMonth()throws Throwable {
int curyear = new Integer(getCurrentYear()).intValue(); // 当前年份
int curMonth = new Integer(getCurrentMonth()).intValue();// 当前月份
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static int getDaysOfMonth(final String time) {
if (time.length() != 6) {
throw new NullPointerException("参数的格式必须是yyyyMM");
}
String[] timeArray = time.split("-");
int curyear = new Integer(time.substring(0, 4)); // 当前年份
int curMonth = new Integer(time.substring(4, 6));// 当前月份
if (curMonth > 12) {
throw new NullPointerException("参数的格式必须是yyyyMM,而且月份必须小于等于12。");
}
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
if (curMonth == 12) {
return mArray[0];
}
return mArray[curMonth - 1];
// 如果要返回下个月的天数,注意处理月份12的情况,防止数组越界;
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static String getLastDayOfMonth(final String yyyy, final String MM) {
int days = getDaysOfMonth(yyyy+MM);
return yyyy + MM +String.valueOf(days);
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 根据指定的年月 返回指定月份(yyyy-MM)有多少天。
*
* @param time
* yyyy-MM
* @return 天数,指定月份的天数。
*/
public static String getFirstDayOfMonth(final String yyyy, final String MM) {
return yyyy + MM + "01";
// 如果要返回上个月的天数,注意处理月份1的情况,防止数组越界;
}
/**
* 返回指定为年度为year月度month的月份内,第weekOfMonth个星期的第dayOfWeek天是当月的几号。<br>
* 00 00 00 01 02 03 04 <br>
* 05 06 07 08 09 10 11<br>
* 12 13 14 15 16 17 18<br>
* 19 20 21 22 23 24 25<br>
* 26 27 28 29 30 31 <br>
* 2006年的第一个周的1到7天为:05 06 07 01 02 03 04 <br>
* 2006年的第二个周的1到7天为:12 13 14 08 09 10 11 <br>
* 2006年的第三个周的1到7天为:19 20 21 15 16 17 18 <br>
* 2006年的第四个周的1到7天为:26 27 28 22 23 24 25 <br>
* 2006年的第五个周的1到7天为:02 03 04 29 30 31 01 。本月没有就自动转到下个月了。
*
* @param year
* 形式为yyyy <br>
* @param month
* 形式为MM,参数值在[1-12]。<br>
* @param weekOfMonth
* 在[1-6],因为一个月最多有6个周。<br>
* @param dayOfWeek
* 数字在1到7之间,包括1和7。1表示星期天,7表示星期六<br>
* -6为星期日-1为星期五,0为星期六 <br>
* @return <type>int</type>
*/
public static int getDayofWeekInMonth(String year, String month, String weekOfMonth, String dayOfWeek) {
Calendar cal = new GregorianCalendar();
// 在具有默认语言环境的默认时区内使用当前时间构造一个默认的 GregorianCalendar。
int y = new Integer(year).intValue();
int m = new Integer(month).intValue();
cal.clear();// 不保留以前的设置
cal.set(y, m - 1, 1);// 将日期设置为本月的第一天。
cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, new Integer(weekOfMonth).intValue());
cal.set(Calendar.DAY_OF_WEEK, new Integer(dayOfWeek).intValue());
// System.out.print(cal.get(Calendar.MONTH)+" ");
// System.out.print("当"+cal.get(Calendar.WEEK_OF_MONTH)+"\t");
// WEEK_OF_MONTH表示当天在本月的第几个周。不管1号是星期几,都表示在本月的第一个周
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 根据指定的年月日小时分秒,返回一个java.Util.Date对象。
*
* @param year
* 年
* @param month
* 月 0-11
* @param date
* 日
* @param hourOfDay
* 小时 0-23
* @param minute
* 分 0-59
* @param second
* 秒 0-59
* @return 一个Date对象。
*/
public static Date getDate(int year, int month, int date, int hourOfDay, int minute, int second) {
Calendar cal = new GregorianCalendar();
cal.set(year, month, date, hourOfDay, minute, second);
return cal.getTime();
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param year
* @param month
* month是从1开始的12结束
* @param day
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String year, String month, String day) {
Calendar cal = new GregorianCalendar(new Integer(year).intValue(), new Integer(month).intValue() - 1,
new Integer(day).intValue());
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
* "yyyy/MM/dd",或者"yyyy-MM-dd"
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(String date) {
String[] temp = null;
if (date.indexOf("/") > 0) {
temp = date.split("/");
}
if (date.indexOf("-") > 0) {
temp = date.split("-");
}
return getDayOfWeek(temp[0], temp[1], temp[2]);
}
/**
* 返回当前日期是星期几。例如:星期日、星期一、星期六等等。
*
* @param date
* 格式为 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 返回当前日期是星期几
*/
public static String getChinaDayOfWeek(String date) {
String[] weeks = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
int week = getDayOfWeek(date);
return weeks[week - 1];
}
/**
* 根据指定的年、月、日返回当前是星期几。1表示星期天、2表示星期一、7表示星期六。
*
* @param date
*
* @return 返回一个代表当期日期是星期几的数字。1表示星期天、2表示星期一、7表示星期六。
*/
public static int getDayOfWeek(Date date) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 返回制定日期所在的周是一年中的第几个周。<br>
* created by wangmj at 20060324.<br>
*
* @param year
* @param month
* 范围1-12<br>
* @param day
* @return int
*/
public static int getWeekOfYear(String year, String month, String day) {
Calendar cal = new GregorianCalendar();
cal.clear();
cal.set(new Integer(year).intValue(), new Integer(month).intValue() - 1, new Integer(day).intValue());
return cal.get(Calendar.WEEK_OF_YEAR);
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @return Date 加上一定天数以后的Date对象.
*/
public static Date getDateAdd(Date date, int amount) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return cal.getTime();
}
/**
* 取得给定日期加上一定天数后的日期对象.
*
* @param date
* 给定的日期对象
* @param amount
* 需要添加的天数,如果是向前的天数,使用负数就可以.
* @param format
* 输出格式.
* @return Date 加上一定天数以后的Date对象.
*/
public static String getFormatDateAdd(Date date, int amount, String format)throws Throwable {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.add(GregorianCalendar.DATE, amount);
return getFormatDateTime(cal.getTime(), format);
}
/**
* 获得当前日期固定间隔天数的日期,如前60天dateAdd(-60)
*
* @param amount
* 距今天的间隔日期长度,向前为负,向后为正
* @param format
* 输出日期的格式.
* @return java.lang.String 按照格式输出的间隔的日期字符串.
*/
public static String getFormatCurrentAdd(int amount, String format)throws Throwable {
Date d = getDateAdd(new Date(), amount);
return getFormatDateTime(d, format);
}
/**
* 取得给定格式的昨天的日期输出
*
* @param format
* 日期输出的格式
* @return String 给定格式的日期字符串.
*/
public static String getFormatYestoday(String format)throws Throwable {
return getFormatCurrentAdd(-1, format);
}
/**
* 返回指定日期的前一天。<br>
*
* @param sourceDate
* @param format
* yyyy MM dd hh mm ss
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getYestoday(String sourceDate, String format)throws Throwable {
return getFormatDateAdd(getDateFromString(sourceDate, format), -1, format);
}
/**
* 返回明天的日期,<br>
*
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatTomorrow(String format)throws Throwable {
return getFormatCurrentAdd(1, format);
}
/**
* 返回指定日期的后一天。<br>
*
* @param sourceDate
* @param format
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getFormatDateTommorrow(String sourceDate, String format)throws Throwable {
return getFormatDateAdd(getDateFromString(sourceDate, format), 1, format);
}
/**
* 根据主机的默认 TimeZone,来获得指定形式的时间字符串。
*
* @param dateFormat
* @return 返回日期字符串,形式和formcat一致。
*/
public static String getCurrentDateString(String dateFormat) {
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(cal.getTime());
}
// /**
// * @deprecated 不鼓励使用。 返回当前时间串 格式:yyMMddhhmmss,在上传附件时使用
// *
// * @return String
// */
// public static String getCurDate() {
// GregorianCalendar gcDate = new GregorianCalendar();
// int year = gcDate.get(GregorianCalendar.YEAR);
// int month = gcDate.get(GregorianCalendar.MONTH) + 1;
// int day = gcDate.get(GregorianCalendar.DAY_OF_MONTH);
// int hour = gcDate.get(GregorianCalendar.HOUR_OF_DAY);
// int minute = gcDate.get(GregorianCalendar.MINUTE);
// int sen = gcDate.get(GregorianCalendar.SECOND);
// String y;
// String m;
// String d;
// String h;
// String n;
// String s;
// y = new Integer(year).toString();
//
// if (month < 10) {
// m = "0" + new Integer(month).toString();
// } else {
// m = new Integer(month).toString();
// }
//
// if (day < 10) {
// d = "0" + new Integer(day).toString();
// } else {
// d = new Integer(day).toString();
// }
//
// if (hour < 10) {
// h = "0" + new Integer(hour).toString();
// } else {
// h = new Integer(hour).toString();
// }
//
// if (minute < 10) {
// n = "0" + new Integer(minute).toString();
// } else {
// n = new Integer(minute).toString();
// }
//
// if (sen < 10) {
// s = "0" + new Integer(sen).toString();
// } else {
// s = new Integer(sen).toString();
// }
//
// return "" + y + m + d + h + n + s;
// }
/**
* 根据给定的格式,返回时间字符串。 和getFormatDate(String format)相似。
*
* @param format
* yyyy MM dd hh mm ss
* @return 返回一个时间字符串
*/
public static String getCurTimeByFormat(String format) {
Date newdate = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(newdate);
}
/**
* 获取两个时间串时间的差值,单位为秒
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static long getDiff(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / 1000;
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return diff;
}
/**
* 获取小时/分钟/秒
*
* @param second
* 秒
* @return 包含小时、分钟、秒的时间字符串,例如3小时23分钟13秒。
*/
public static String getHour(long second) {
long hour = second / 60 / 60;
long minute = (second - hour * 60 * 60) / 60;
long sec = (second - hour * 60 * 60) - minute * 60;
return hour + "小时" + minute + "分钟" + sec + "秒";
}
/**
*
* 获取小时/分钟/秒/MS
*
*
*
* @param ms
*
* 秒
*
* @return 包含小时、分钟、秒的时间字符串,例如00h02m35s839ms。
*/
public static String getMsHour(long ms) {
long lms = ms % 1000;
long lm = ms / 1000;
long hour = lm / 60 / 60;
long minute = (lm - hour * 60 * 60) / 60;
long sec = (lm - hour * 60 * 60) - minute * 60;
String strHour = "h";
String strMinute = "m";
String strSec = "s";
String strLms = "ms";
if (hour < 10) {
strHour = "0" + hour + strHour;
} else {
strHour = hour + strHour;
}
if (minute < 10) {
strMinute = "0" + minute + strMinute;
} else {
strMinute = minute + strMinute;
}
if (sec < 10) {
strSec = "0" + sec + strSec;
} else {
strSec = sec + strSec;
}
if (lms < 10) {
strLms = "00" + lms + strLms;
} else if (lms < 100) {
strLms = "0" + lms + strLms;
} else {
strLms = lms + strLms;
}
String retVal = "0";
if (strHour.contains("00") == false) {
retVal += strHour;
}
if (strMinute.contains("00") == false) {
retVal += strMinute;
}
if (strSec.contains("00") == false) {
retVal += strSec;
}
if (strLms.contains("000") == false) {
retVal += strLms;
}
if ("0".equals(retVal)) {
retVal = "0ms";
} else {
retVal = CmnStrUtils.trimLeftChar(retVal,"0");
}
return retVal;
}
/**
* 返回指定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getDateTime(long microsecond)throws Throwable {
return getFormatDateTime(new Date(microsecond), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回指定时间字符串。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return String 指定格式的日期字符串.
*/
public static String getDateTime(long microsecond, String pattarn)throws Throwable {
return getFormatDateTime(new Date(microsecond), pattarn);
}
/**
* 返回当前时间加实数小时后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return Float 加几实数小时.
*/
public static String getDateByAddFltHour(float flt)throws Throwable {
int addMinute = (int) (flt * 60);
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(GregorianCalendar.MINUTE, addMinute);
return getFormatDateTime(cal.getTime(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 返回指定时间加指定小时数后的日期时间。
* <p>
* 格式:yyyy-MM-dd HH:mm:ss
*
* @return 时间.
*/
public static String getDateByAddHour(String datetime, String pattarn, int minute)throws Throwable {
String returnTime = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat ft = new SimpleDateFormat(pattarn);
Date date;
try {
date = ft.parse(datetime);
cal.setTime(date);
cal.add(GregorianCalendar.MINUTE, minute);
returnTime = getFormatDateTime(cal.getTime(), pattarn);
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return returnTime;
}
/**
* 获取两个时间串时间的差值,单位为小时
*
* @param startTime
* 开始时间 yyyy-MM-dd HH:mm:ss
* @param endTime
* 结束时间 yyyy-MM-dd HH:mm:ss
* @return 两个时间的差值(秒)
*/
public static int getDiffHour(String startTime, String endTime) {
long diff = 0;
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date startDate = ft.parse(startTime);
Date endDate = ft.parse(endTime);
diff = startDate.getTime() - endDate.getTime();
diff = diff / (1000 * 60 * 60);
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return new Long(diff).intValue();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @return 年份下拉框的html
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* 例如开始年份为2001结束年份为2005那么下拉框就有五个值。(2001、2002、2003、2004、2005)。
* @return 返回年份的下拉框的html。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, boolean hasBlank,
String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 返回年份的下拉框。
*
* @param selectName
* 下拉框名称
* @param value
* 当前下拉框的值
* @param startYear
* 开始年份
* @param endYear
* 结束年份
* @param js
* 这里的js为js字符串。例如 " onchange=\"changeYear()\" "
* ,这样任何js的方法就可以在jsp页面中编写,方便引入。
* @return 返回年份的下拉框。
*/
public static String getYearSelect(String selectName, String value, int startYear, int endYear, String js) {
int start = startYear;
int end = endYear;
if (startYear > endYear) {
start = endYear;
end = startYear;
}
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
for (int i = start; i <= end; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取月份的下拉框
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 返回月份的下拉框。
*/
public static String getMonthSelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 12; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得天的下拉框
*/
public static String getDaySelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取天的下拉框,默认的为1-31
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取天的下拉框
*/
public static String getDaySelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 31; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 计算两天之间有多少个周末(这个周末,指星期六和星期天,一个周末返回结果为2,两个为4,以此类推。) (此方法目前用于统计司机用车记录。)
* 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 开始日期 ,格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 结束日期 ,格式"yyyy/MM/dd"或者"yyyy-MM-dd"
* @return int
*/
public static int countWeekend(String startDate, String endDate) {
int result = 0;
Date sdate = null;
Date edate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
edate = getDateObj(endDate, "/");// 结束日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
edate = getDateObj(endDate, "-");// 结束日期
}
// 首先计算出都有那些日期,然后找出星期六星期天的日期
int sumDays = Math.abs(getDiffDays(startDate, endDate));
int dayOfWeek = 0;
for (int i = 0; i <= sumDays; i++) {
dayOfWeek = getDayOfWeek(getDateAdd(sdate, i)); // 计算每过一天的日期
if (dayOfWeek == 1 || dayOfWeek == 7) { // 1 星期天 7星期六
result++;
}
}
return result;
}
/**
* 计算两个日期之间相差的天数
* @param smdate 较小的时间
* @param bdate 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static int daysBetween(Date smdate,Date bdate) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
smdate=sdf.parse(sdf.format(smdate));
bdate=sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
*字符串的日期格式的计算
*/
public static int daysBetween(String smdate,String bdate) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 返回两个日期之间相差多少天。 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @param endDate
* 格式"yyyy/MM/dd" 或者"yyyy-MM-dd"
* @return 整数。
*/
public static int getDiffDays(String startDate, String endDate) {
long diff = 0;
SimpleDateFormat ft = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
ft = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try {
Date sDate = ft.parse(startDate + " 00:00:00");
Date eDate = ft.parse(endDate + " 00:00:00");
diff = eDate.getTime() - sDate.getTime();
diff = diff / 86400000;// 1000*60*60*24;
} catch (ParseException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return (int) diff;
}
/**
* 返回两个日期之间的详细日期数组(包括开始日期和结束日期)。 例如:2007/07/01 到2007/07/03 ,那么返回数组
* {"2007/07/01","2007/07/02","2007/07/03"} 注意开始日期和结束日期要统一起来。
*
* @param startDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @param endDate
* 格式"yyyy/MM/dd"或者 yyyy-MM-dd
* @return 返回一个字符串数组对象
*/
public static String[] getArrayDiffDays(String startDate, String endDate)throws Throwable {
int LEN = 0; // 用来计算两天之间总共有多少天
// 如果结束日期和开始日期相同
if (startDate.equals(endDate)) {
return new String[] { startDate };
}
Date sdate = null;
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
sdate = getDateObj(startDate, "/"); // 开始日期
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
sdate = getDateObj(startDate, "-"); // 开始日期
}
LEN = getDiffDays(startDate, endDate);
String[] dateResult = new String[LEN + 1];
dateResult[0] = startDate;
for (int i = 1; i < LEN + 1; i++) {
if (startDate.indexOf("/") > 0 && endDate.indexOf("/") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i), "yyyy/MM/dd");
}
if (startDate.indexOf("-") > 0 && endDate.indexOf("-") > 0) {
dateResult[i] = getFormatDateTime(getDateAdd(sdate, i), "yyyy-MM-dd");
}
}
return dateResult;
}
/**
* 判断一个日期是否在开始日期和结束日期之间。
*
* @param srcDate
* 目标日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param startDate
* 开始日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @param endDate
* 结束日期 yyyy/MM/dd 或者 yyyy-MM-dd
* @return 大于等于开始日期小于等于结束日期,那么返回true,否则返回false
*/
public static boolean isInStartEnd(String srcDate, String startDate, String endDate) {
if (startDate.compareTo(srcDate) <= 0 && endDate.compareTo(srcDate) >= 0) {
return true;
} else {
return false;
}
}
/**
* 获取天的下拉框,默认的为1-4。 注意:此方法不能够和月份下拉框进行联动。
*
* @param selectName
* @param value
* @param hasBlank
* @return 获得季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value, boolean hasBlank) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 获取季度的下拉框,默认的为1-4
*
* @param selectName
* @param value
* @param hasBlank
* @param js
* @return 获取季度的下拉框
*/
public static String getQuarterSelect(String selectName, String value, boolean hasBlank, String js) {
StringBuffer sb = new StringBuffer("");
sb.append("<select name=\"" + selectName + "\" " + js + ">");
if (hasBlank) {
sb.append("<option value=\"\"></option>");
}
for (int i = 1; i <= 4; i++) {
if (!value.trim().equals("") && i == Integer.parseInt(value)) {
sb.append("<option value=\"" + i + "\" selected>" + i + "</option>");
} else {
sb.append("<option value=\"" + i + "\">" + i + "</option>");
}
}
sb.append("</select>");
return sb.toString();
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDate(String argDate) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + "/01/01";
}
if (LEN == 2) {
result = str[0] + "/" + str[1] + "/01";
}
if (LEN == 3) {
result = str[0] + "/" + str[1] + "/" + str[2];
}
return result;
}
/**
* 将格式为yyyy或者yyyy.MM或者yyyy.MM.dd的日期转换为yyyy/MM/dd的格式。位数不足的,都补01。<br>
* 例如.1999 = 1999/01/01 再如:1989.02=1989/02/01
*
* @param argDate
* 需要进行转换的日期。格式可能为yyyy或者yyyy.MM或者yyyy.MM.dd
* @return 返回格式为yyyy/MM/dd的字符串
*/
public static String changeDateWithSplit(String argDate, String split) {
if (argDate == null || argDate.trim().equals("")) {
return "";
}
if (split == null || split.trim().equals("")) {
split = "-";
}
String result = "";
// 如果是格式为yyyy/MM/dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("/") > 0) {
return argDate;
}
// 如果是格式为yyyy-MM-dd的就直接返回
if (argDate.length() == 10 && argDate.indexOf("-") > 0) {
return argDate;
}
String[] str = argDate.split("[.]"); // .比较特殊
int LEN = str.length;
for (int i = 0; i < LEN; i++) {
if (str[i].length() == 1) {
if (str[i].equals("0")) {
str[i] = "01";
} else {
str[i] = "0" + str[i];
}
}
}
if (LEN == 1) {
result = argDate + split + "01" + split + "01";
}
if (LEN == 2) {
result = str[0] + split + str[1] + split + "01";
}
if (LEN == 3) {
result = str[0] + split + str[1] + split + str[2];
}
return result;
}
/**
* 返回指定日期的的下一个月的天数。
*
* @param argDate
* 格式为yyyy-MM-dd或者yyyy/MM/dd
* @return 下一个月的天数。
*/
public static int getNextMonthDays(String argDate) {
String[] temp = null;
if (argDate.indexOf("/") > 0) {
temp = argDate.split("/");
}
if (argDate.indexOf("-") > 0) {
temp = argDate.split("-");
}
Calendar cal = new GregorianCalendar(new Integer(temp[0]).intValue(), new Integer(temp[1]).intValue() - 1,
new Integer(temp[2]).intValue());
int curMonth = cal.get(Calendar.MONTH);
cal.set(Calendar.MONTH, curMonth + 1);
int curyear = cal.get(Calendar.YEAR);// 当前年份
curMonth = cal.get(Calendar.MONTH);// 当前月份,0-11
int mArray[] = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年的情况 ,2月份有29天;
if ((curyear % 400 == 0) || ((curyear % 100 != 0) && (curyear % 4 == 0))) {
mArray[1] = 29;
}
return mArray[curMonth];
}
public static String getDateStr(String str) {
str=str.replace("/", "");
//System.out.println(str);
str=str.replace("\\", "");
//System.out.println(str);
str=str.replace("-", "");
//System.out.println(str);
str=str.replace(" ", "");
//System.out.println(str);
str=str.replace(":", "");
//System.out.println(str);
return str;
}
public static boolean isDateNumber(String str) {
boolean isDateNumber = false;
String s = getDateStr(str);
int len = str.length();
if (len == {
} else if (len ==14) {
}
return isDateNumber;
}
public static String convJtGDate(String src) throws ParseException {
Integer gc = 0;
String gg = src.substring(0, 2);
Integer yy = Integer.parseInt(src.substring(2, src.indexOf("年")));
Integer mm = Integer.parseInt(src.substring(src.indexOf("年") + 1,
src.indexOf("月")));
Integer dd = Integer.parseInt(src.substring(src.indexOf("月") + 1,
src.indexOf("日")));
if (gg.equals("平成")) {
gc = 4;
} else if (gg.equals("昭和")) {
gc = 3;
} else if (gg.equals("大正")) {
gc = 2;
} else if (gg.equals("明治")) {
gc = 1;
}
Locale.setDefault(new Locale("ja", "JP", "JP"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.ERA, gc);
cal.set(yy, mm - 1, dd);
Locale.setDefault(new Locale("en", "EN", "EN"));
SimpleDateFormat gdf = new SimpleDateFormat("yyyy/MM/dd");
return gdf.format(cal.getTime());
}
public static String convGtJDate(String src) throws ParseException {
Locale.setDefault(new Locale("en", "EN", "EN"));
SimpleDateFormat gdf = new SimpleDateFormat("yyyyMMdd");
Locale.setDefault(new Locale("ja", "JP", "JP"));
SimpleDateFormat jdf = new SimpleDateFormat("GGGGyy年MM月dd日");
return jdf.format(gdf.parse(src.replace("/", "")));
}
}
-------C:\aa\common\CmnFileUtils.java
/**
* Copyright (c) 2012, Java CNC/CSJ for tools. All rights reserved.
*/
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import jp.co.csj.tools.utils.common.CsjPath;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.file.core.CsjSameFilesInfo;
import jp.co.csj.tools.utils.key.CsjDesEncrypt;
import jp.co.csj.tools.utils.msg.dbtools.CsjDbToolsMsg;
import jp.co.csj.tools.utils.reg.RegConstStr;
/**
* CsjDirectory
* @author cuishuangjia@163.com
* @version 1.0
* @since 1.6
*/
public class CmnFileUtils {
public static void main(String[] args) {
try {
CmnLog5j.initLog5j("log.txt", IConstFile.ENCODE_UTF_8);
List<File> fileLst = getFilesList("C:\\aa", true);
for (File f: fileLst) {
try {
List<String> strlst = getFileContent(f, IConstFile.ENCODE_UTF_8);
for(String s : strlst) {
CmnLog5j.writeLine(s);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
CmnLog5j.closeLog5j();
}
}
public static LinkedList<File> getFilesListWithOutStr(String filePath,
boolean isHaveSubFile, String startStr, String endStr) {
LinkedList<File> tList = getFilesList(filePath, isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isNotEmpty(startStr) && fNm.startsWith(startStr)) {
continue;
} else if (CmnStrUtils.isNotEmpty(endStr) && fNm.endsWith(endStr)) {
continue;
}
}
return retList;
}
public static boolean isFiles(String text, String splitStr) {
boolean retVal = true;
String[] strArr = text.split(splitStr);
for (String str : strArr) {
if (CmnStrUtils.isEmpty(str)) {
continue;
}
File f = new File(str);
if (f.isFile() == false) {
retVal = false;
break;
}
}
return retVal;
}
/**
* * @param
*/
public static int checkFilePath(String filePath) {
int retVal = IConstFile.IS_ERROR;
File f = new File(filePath);
if (f.isDirectory()) {
retVal = IConstFile.IS_PATH;
} else if (f.isFile()) {
retVal = IConstFile.IS_FILE;
} else if (filePath.contains(";") && isFiles(filePath, ";")) {
retVal = IConstFile.IS_FILES;
}
return retVal;
}
public static LinkedList<File> getExcelFileByAbsPath(String filePath,boolean isHaveSubFile) {
LinkedList<File> retList = new LinkedList<File>();
int retVal = checkFilePath(filePath);
if (retVal == IConstFile.IS_PATH) {
retList= getFilesListReg(filePath, isHaveSubFile,RegConstStr.EXCEL_REG_DOT);
} else if (retVal == IConstFile.IS_FILE) {
retList.add(new File(filePath));
} else if (retVal == IConstFile.IS_FILES) {
String[] strArr = filePath.split(",");
for (String str : strArr) {
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(new File(str));
}
}
}
return retList;
}
public static LinkedList<File> getFilesListWithStr(String filePath,
boolean isHaveSubFile,String startStr,String endStr) {
LinkedList<File> tList =getFilesList(filePath,isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isNotEmpty(startStr)&& fNm.startsWith(startStr)) {
retList.add(f);
} else if (CmnStrUtils.isNotEmpty(endStr)&& fNm.endsWith(endStr)) {
retList.add(f);
}
}
return retList;
}
public static TreeMap<Long,File> getFilesModifyTimeMapReg(String filePath,
boolean isHaveSubFile,String regex) {
LinkedList<File> tList =getFilesList(filePath,isHaveSubFile);
TreeMap<Long,File> retMap = new TreeMap<Long, File>();
for (File f : tList) {
String fNm = f.getName().toLowerCase();
if (CmnStrUtils.isEmpty(regex)||fNm.matches(regex)) {
retMap.put(f.lastModified(), f);
}
}
return retMap;
}
public static LinkedList<File> getFilesListReg(String filePath,
boolean isHaveSubFile,String regex) {
LinkedList<File> fList = getFilesList(filePath,isHaveSubFile);
LinkedList<File> retList = new LinkedList<File>();
for (File f : fList) {
if (CmnStrUtils.isEmpty(regex)||f.getName().matches(regex)) {
retList.add(f);
}
}
return retList;
}
/**
* @param String filePath
* @param boolean isHaveSubFile
* @return
*/
public static LinkedList<File> getFilesList(String filePath,
boolean isHaveSubFile) {
LinkedList<File> retList = new LinkedList<File>();
LinkedList<File> list = new LinkedList<File>();
File dir = new File(filePath);
File file[] = dir.listFiles();
if (null == file) {
return retList;
}
for (int i = 0; i < file.length; i++) {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
if (file[i].isDirectory())
list.add(file[i]);
else
retList.add(file[i]);
}
if (isHaveSubFile) {
File tmp;
while (!list.isEmpty()) {
tmp = list.removeFirst();
if (tmp.isDirectory()) {
file = tmp.listFiles();
if (file == null)
continue;
for (int i = 0; i < file.length; i++) {
if (file[i].isDirectory())
list.add(file[i]);
else {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
retList.add(file[i]);
}
}
} else {
// if (tmp.getName().endsWith(".scc")) {
// continue;
// }
retList.add(tmp);
}
}
}
return retList;
}
public static boolean reNameFile(File f, String newNm) {
File mm = new File(f.getParent() + CsjProcess.s_f_s + newNm);
return f.renameTo(mm);
}
// /**
// *
// * @param filePathList
// * @return
// */
// public static LinkedList<File> getFilesList(List<String> filePathList, boolean isHaveSubFile) {
// LinkedList<File> retList = new LinkedList<File>();
// for (String filePath : filePathList) {
// LinkedList<File> fileList = getFilesList(filePath, isHaveSubFile);
// for (File file : fileList) {
// retList.add(file);
// }
// }
// return retList;
// }
//
// /**
// *
// * @param filePath
// * @return
// */
// public static LinkedList<File> getFilesList(String filePath,
// boolean isHaveSubFile) {
//
// LinkedList<File> retList = new LinkedList<File>();
// LinkedList<File> list = new LinkedList<File>();
// File dir = new File(filePath);
// File file[] = dir.listFiles();
// if (null == file) {
// System.out.println("a");
// }
//
// for (int i = 0; i < file.length; i++) {
//
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
//
// if (file[i].isDirectory())
// list.add(file[i]);
// else
// retList.add(file[i]);
// }
//
// if (isHaveSubFile) {
// File tmp;
// while (!list.isEmpty()) {
// tmp = list.removeFirst();
//
// if (tmp.isDirectory()) {
// file = tmp.listFiles();
// if (file == null)
// continue;
// for (int i = 0; i < file.length; i++) {
// if (file[i].isDirectory())
// list.add(file[i]);
// else {
// if (file[i].getName().endsWith(".scc")) {
// continue;
// }
// retList.add(file[i]);
// }
// }
// } else {
// if (tmp.getName().endsWith(".scc")) {
// continue;
// }
// retList.add(tmp);
// }
// }
// }
//
// return retList;
// }
public static LinkedHashMap<String, File> getFilesMap(String filePath, boolean isHaveSubFile) {
LinkedHashMap<String, File> retMap = new LinkedHashMap<String, File>();
List<File> fileList = getFilesList(filePath, isHaveSubFile);
for (File f : fileList) {
retMap.put(f.getName(), f);
}
return retMap;
}
public static Map<String, File> getFilesTreeMap(String filePath, boolean isHaveSubFile) {
Map<String, File> retMap = new TreeMap<String, File>();
List<File> fileList = getFilesList(filePath, isHaveSubFile);
for (File f : fileList) {
retMap.put(f.getName(), f);
}
return retMap;
}
public static long getFileSizes(File f) {// 取得文件大小
long s = 0;
FileInputStream fis = null;
try {
if (f.exists()) {
fis = new FileInputStream(f);
s = fis.available();
} else {
f.createNewFile();
System.out.println("file not exist!");
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
CmnLog.logger.info(e.getMessage());
}
}
return s;
}
public static String formatFileSize(long fileS) {// 转换文件大小
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
public static String getFileSize(File f) {
return formatFileSize(getFileSizes(f));
}
public static long getFileMaxLine(File f) {
long retVal = 0;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f), IConstFile.ENCODE_SHIFT_JIS));
while (reader.ready()) {
reader.readLine();
retVal++;
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retVal;
}
public static void removeFiles(String filePath) throws Throwable {
try {
File f = new File(filePath);
if (f!=null) {
delFile(f);
}
} catch (Throwable e) {
throw e;
}
}
public static void delFile(String path,String fileNmReg,boolean haveSub) throws Throwable {
try {
File f = new File(path);
if (CmnStrUtils.isEmpty(fileNmReg)) {
delFile(f);
}else if (f.isDirectory()) {
List<File> fLst = getFilesList(f.getAbsolutePath(), haveSub);
for (File ft : fLst) {
if (CmnStrUtils.isEmpty(fileNmReg)) {
ft.delete();
}else if (ft.getName().matches(fileNmReg)) {
ft.delete();
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static void delFile(File f)throws Throwable {
try {
if (f == null) {
return;
}
if (f.isDirectory()) {
File[] list = f.listFiles();
for (int i = 0; i < list.length; i++) {
if (list[i].isDirectory()) {
delFile(list[i]);
}else{
if(list[i].isFile())
list[i].delete();
}
}
f.delete();
} else {
if (f.isFile())
f.delete();
}
} catch (Throwable e) {
throw e;
}
}
/**
* @param text
* @param string
* @throws Throwable
*/
public static void copyDbtoolsInfo(String newIniNm, String iniText) throws Throwable {
if (CmnStrUtils.isNotEmpty(iniText)) {
copyFile(CsjPath.s_file_db_info_path, iniText + ".xml", CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
} else {
LinkedList<File> fileList = CmnFileUtils.getFilesListWithStr(CsjPath.s_file_db_info_path, false, "", IConstFile.DOT_INI);
if (fileList.size()!=0) {
File f = fileList.get(0);
copyFile(CsjPath.s_file_db_info_path, f.getName(), CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
} else {
fileList = CmnFileUtils.getFilesListWithStr(CsjPath.s_file_db_info_path, false, "", IConstFile.DOT_INI_BAK);
File f = fileList.get(0);
copyFile(CsjPath.s_file_db_info_path, f.getName(), CsjPath.s_file_db_info_path, newIniNm+ ".xml", IConstFile.ENCODE_UTF_8);
}
}
}
private static String formatToFolder(String folder) {
if (folder.endsWith(CsjProcess.s_f_s)) {
return folder;
} else {
return folder + CsjProcess.s_f_s;
}
}
/**
* @param fromFolder
* @param fromFile
* @param toFolder
* @param toFile
* @throws Throwable
*/
public static void copyFile(String fromFolder, String fromFile,
String toFolder, String toFile,boolean toFolderAutoCreate) throws Throwable {
try {
if (toFolderAutoCreate) {
File makeFolder = new File(toFolder);
makeFolder.mkdirs();
}
boolean isHaveSubFile = false;
if (fromFolder.toLowerCase().startsWith("havesub:")) {
isHaveSubFile = true;
}
fromFolder = CmnStrUtils.fromAtoBByTrim(fromFolder,"havesub:", "");
boolean isReg = false;
if (fromFile.startsWith("reg:")) {
isReg = true;
}
fromFile = CmnStrUtils.fromAtoBByTrim(fromFile,"reg:", "");
String fromStr = formatToFolder(fromFolder)+fromFile;
if (isReg) {
fromStr = formatToFolder(fromFolder);
}
String toStr = formatToFolder(toFolder)+toFile;
File from = new File(fromStr);
File to = new File(toStr);
if (from.isDirectory()) {
if (to.isDirectory()) {
if (isReg) {
LinkedList<File> fileLst = getFilesListReg(fromFolder, isHaveSubFile,fromFile);
for (File f : fileLst) {
String toPath = toStr+CmnStrUtils.fromAtoBByTrim(f.getParent()+CsjProcess.s_f_s, fromStr, "");
new File(toPath).mkdirs();
String batStr = "xcopy " + f.getAbsolutePath() + " " + toPath + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
}
} else {
LinkedList<File> fileLst = getFilesList(fromFolder, isHaveSubFile);
for (File f : fileLst) {
String toPath = toStr+CmnStrUtils.fromAtoBByTrim(f.getParent()+CsjProcess.s_f_s, fromStr, "");
new File(toPath).mkdirs();
String batStr = "xcopy " + f.getAbsolutePath() + " " + toPath + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
}
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000111) + CmnLog5j.addlrBracketsM(toStr, false));
}
} else if (from.isFile()) {
if (to.isDirectory()) {
String batStr = "xcopy " + from.getAbsolutePath() + " " + to + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
} else {
File tmpToFolder = new File(toFolder);
if (tmpToFolder.isDirectory()) {
String batStr = "xcopy " + from.getAbsolutePath() + " " + toFolder + " /y /k /c /R";
Process process = Runtime.getRuntime().exec(batStr);
process.waitFor();
File f = new File(toFolder+toFile);
if (f.isFile()) {
f.delete();
}
File fr = new File(toFolder+fromFile);
if (fr.isFile()) {
fr.renameTo(f);
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000113) + CmnLog5j.addlrBracketsM(toFolder, false));
}
}
} else {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000112) + CmnLog5j.addlrBracketsM(fromStr, false));
}
} catch (Throwable e) {
throw e;
}
}
////////////////////////////
public static void writeWithbBlank(BufferedWriter writer, String str,
int blankCount) {
if (writer == null) {
return;
}
try {
writer.write(getBlank(str, blankCount, true));
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
}
public static String getTxtFileInfo(String fileNm, String encode,
String splitLine) throws Throwable {
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(fileNm), encode));
while (reader.ready()) {
buffer.append(reader.readLine() + splitLine);
}
return buffer.toString();
}
public static String getBlank(String str, int blankCount, boolean isBefore) {
String strBlank = CsjConst.EMPTY;
for (int i = 0; i < blankCount; i++) {
strBlank += CsjConst.SIGN_SPACE_4;
}
if (isBefore) {
return strBlank + str;
} else {
return str + strBlank;
}
}
/**
* @param writer
* @param copyRightList
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer,
List<String> strList, int blankCount) {
for (String str : strList) {
writeWithbBlank(writer, str, blankCount);
}
}
/**
* @param writer
* @param copyRightList
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer, String paraStr,
List<String> strList, int blankCount,
boolean isLeft) {
for (String str : strList) {
if (isLeft) {
writeWithbBlank(writer, paraStr + str, blankCount);
} else {
writeWithbBlank(writer, str + paraStr, blankCount);
}
}
}
/**
* @param writer
* @param importMap
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer, String paraStr,
Map<String, String> map, int blankCount,
boolean isLeft) {
for (Entry<String, String> entry : map.entrySet()) {
if (isLeft) {
writeWithbBlank(writer, paraStr + entry.getKey(), blankCount);
} else {
writeWithbBlank(writer, entry.getKey() + paraStr, blankCount);
}
}
}
/**
* @param writer
* @param importMap
* @param blankCount
*/
public static void writeWithbBlank(BufferedWriter writer,
Map<String, String> map, int blankCount) {
for (Entry<String, String> entry : map.entrySet()) {
writeWithbBlank(writer, entry.getKey(), blankCount);
}
}
public static LinkedHashMap<String, String> getFileMap(String filePath,
String encode, boolean isKeyLineNo) {
LinkedHashMap<String, String> retMap = new LinkedHashMap<String, String>();
long retVal = 0;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
while (reader.ready()) {
if (isKeyLineNo) {
retMap.put(String.valueOf(retVal++), reader.readLine());
} else {
retMap.put(reader.readLine(), String.valueOf(retVal++));
}
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
}
return retMap;
}
public static LinkedHashMap<String, List<String>> getKeyFileMap(
String filePath, String encode) {
LinkedHashMap<String, List<String>> retMap = new LinkedHashMap<String, List<String>>();
CmnLog.logger.info(new File(filePath).getAbsolutePath());
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
while (reader.ready()) {
String line = reader.readLine();
CmnLog.logger.info(line);
if (CmnStrUtils.isNotEmpty(line)) {
String strLine = CsjDesEncrypt.uncode(line);
strLine = CmnLanIPUtils.unLongStrKey(strLine);
String str[] = strLine.split(CsjConst.SIGN_AT);
if (str.length == 4) {
// CsjLog4j.info(CsjDesEncrypt.uncode(line).toString());
List<String> list = new ArrayList<String>();
list.add(str[1]);
list.add(str[2]);
retMap.put(str[0], list);
}
}
// if (line != null && line.length() == 80) {
// String key = line.substring(0, 48);
// System.out.println(CsjDesEncrypt.uncode(key));
// String pay = line.substring(48, 64);
// System.out.println(CsjDesEncrypt.uncode(key));
// String date = line.substring(64,96);
// System.out.println(CsjDesEncrypt.uncode(key));
// retMap.put(key,pay+"|||"+date);
// }
}
reader.close();
} catch (Throwable e) {
e.printStackTrace();
}
return retMap;
}
public static void writeFile(String logPath, String fileNm, String enCode,
List<String> strList) throws Throwable {
File file = new File(logPath);
file.mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logPath + fileNm), enCode));
for (String str : strList) {
writeWithbBlank(writer, str, 0);
}
writer.close();
}
public static boolean isFileExist(String filePath) {
return new File(filePath).isFile();
}
public static boolean isFolderExist(String folderPath) {
return new File(folderPath).isDirectory();
}
public static void reWriteFile(String filePath, String enCode,
Map<String,String> regexMap,String cr) throws Throwable {
List<String> strLst = getFileContent(filePath, enCode);
List<String> strLstTmp = new ArrayList<String>();
for (String s:strLst) {
for (String key : regexMap.keySet()) {
if (s.matches(key)) {
s = regexMap.get(key);
break;
}
}
strLstTmp.add(s);
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), enCode));
for (String str : strLstTmp) {
writer.write(str);
writer.write(cr);
}
writer.close();
}
public static String getFileNm(String filePath) {
String retVal = CsjConst.EMPTY;
File file = new File(filePath);
retVal = file.getName();
return retVal;
}
public static boolean
isTwoFileNmSame(String fileOldPath, String filNewPath) {
return getFileNm(fileOldPath).equals(getFileNm(filNewPath));
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
*/
public static List<CsjSameFilesInfo> getSameFile(
LinkedHashMap<String, File> oldFilesMap,
LinkedHashMap<String, File> newFilesMap) {
List<CsjSameFilesInfo> retList = new ArrayList<CsjSameFilesInfo>();
for (Entry<String, File> entry : newFilesMap.entrySet()) {
String key = entry.getKey();
if (oldFilesMap.containsKey(key)) {
CsjSameFilesInfo csjSameFilesInfo = new CsjSameFilesInfo();
csjSameFilesInfo.setFileNm(key);
csjSameFilesInfo.getFilePaths().add(
oldFilesMap.get(key).getAbsolutePath());
csjSameFilesInfo.getFilePaths().add(
newFilesMap.get(key).getAbsolutePath());
retList.add(csjSameFilesInfo);
}
}
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFileContent(File f, String encode)
throws Throwable {
List<String> retList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f),
encode));
while (reader.ready()) {
retList.add(reader.readLine());
}
reader.close();
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFileContent(String path, String encode)
throws Throwable {
List<String> retList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(path)),
encode));
while (reader.ready()) {
retList.add(reader.readLine());
}
reader.close();
return retList;
}
public static Map<Integer,String> getFileContents(String filePath,String splitCh,int col,int rowStart,int rowEnd,String encode) throws Throwable {
Map<Integer,String> retMap = new HashMap<Integer, String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(filePath)),
encode));
int i = 0;
while (reader.ready()) {
String line = reader.readLine();
if (i >= rowStart && i <= rowEnd) {
String[] sa = line.split(splitCh);
if (col < sa.length ) {
retMap.put(i-rowStart, sa[col]);
}
}
i++;
}
reader.close();
return retMap;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static List<String> getFilesContent(String path, String encode)
throws Throwable {
List<File> fileList = CmnFileUtils.getFilesList(path, false);
List<String> retList = new ArrayList<String>();
for (File f : fileList) {
List<String> strList = getFileContent(f, encode);
for (String str : strList) {
retList.add(str);
}
}
return retList;
}
/**
* @param oldFilesMap
* @param newFilesMap
* @return
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void copyFile(String path, String nm, String newPath,
String newNm, String encode) throws Throwable {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(path + nm),
encode));
File file = new File(newPath);
file.mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(newPath + newNm), encode));
while (reader.ready()) {
writeWithbBlank(writer, reader.readLine(), 0);
}
writer.close();
reader.close();
}
/**
* @param fileMap
* @param string
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void createFile(TreeMap<Long, File> fileMap, String outputFileName, String encode) throws Throwable {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), encode));
for (File f : fileMap.values()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f.getAbsolutePath()),encode));
while (reader.ready()) {
String line = reader.readLine();
CmnLog5j.writeLine(writer, line);
}
reader.close();
}
CmnLog5j.close(writer);
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnLanIPUtils.java
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import jp.co.csj.tools.utils.common.CsjCheck;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.key.CsjDesEncrypt;
import jp.co.csj.tools.utils.reg.RegConstStr;
import jp.co.csj.utils.exe.net.CsjMacAddress;
/**
* 使用java线程扫描局域网ip简单方案
*
* @author Administrator
*
*/
public class CmnLanIPUtils {
public static long step = 0;
public static String proty = CsjProcess.s_pj_path + "properties"
+ CsjProcess.s_f_s;
public static String keyNm = "key.dll";
public static String keyTNm = "keyT.dll";
public static String s_file_key_T_file = "properties" + CsjProcess.s_f_s
+ keyTNm;
public static String s_file_key_file = "properties" + CsjProcess.s_f_s
+ "key.dll";
public static boolean isAccessNet=false;
/**
* @throws Throwable
*/
public static void writeLimitDate() throws Throwable {
List<String> strList = new ArrayList<String>();
strList.add(CsjDesEncrypt.encode(enLongStrKey(CsjCheck.limitDate, 10)));
String folder = CsjProcess.s_pj_path + "properties"
+ CsjProcess.s_f_s;
System.out.println(folder);
CmnFileUtils.writeFile(folder, keyTNm, IConstFile.ENCODE_UTF_8,
strList);
}
/**
* @throws Throwable
*/
public static void writeLocalMacKey(String key) throws Throwable {
List<String> strList = new ArrayList<String>();
strList.add(key);
CmnFileUtils
.writeFile(proty, keyNm, IConstFile.ENCODE_UTF_8, strList);
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String getOneKey(boolean isPayMoney, String strMac,
String strDate) throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String stepStr = CmnRandomUtils.createRadomStrs(6, true, false);
String strPre = "unpay";
if (isPayMoney) {
strPre = "payed";
}
strMac = strMac.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
String str = strMac + CsjConst.SIGN_AT + strMac1 + strPre
+ CsjConst.SIGN_AT + strMac2 + strDate + CsjConst.SIGN_AT
+ stepStr;
System.out.println(strMac);
System.out.println(strPre);
System.out.println(strDate);
System.out.println(stepStr);
System.out.println(str);
str = enLongStrKey(str,10);
str = CsjDesEncrypt.encode(str);
System.out.println(str);
return str;
}
/**
* @param str
* @param level
* @return
*/
public static String enLongStrKey(String str, int level) {
for (int i = 0; i < CsjConst.SIGN_RANDOM.length; i++) {
for (int index = 0; index < level; index++) {
int num = CmnRandomUtils.createRadomNum(CsjConst.SIGN_RANDOM.length, true);
str = CmnStrUtils.insertChar(str,CsjConst.SIGN_RANDOM[num],CmnRandomUtils.createRadomNum(str.length(), true)%str.length());
}
}
return str;
}
/**
* @param strLine
* @return
*/
public static String unLongStrKey(String strLine) {
for (int i = 0; i < CsjConst.SIGN_RANDOM.length; i++) {
strLine=CmnStrUtils.funReplace(strLine, CsjConst.SIGN_RANDOM[i], "");
}
return strLine;
}
public static void main(String[] args) {
String strMac = "00-26-C7-72-DC-D4";
strMac = strMac.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
System.out.println(strMac1);
System.out.println(strMac2);
System.out.println("abcdefghi".substring(3));
// if ("192.168.20.123s".matches(RegConstStr.IP)) {
// System.out.println("ok");
// }
try {
writeLimitDate();
// writeLocalMacKey(getOneKey());
System.out.println("REGEDIT SUCCESS");
// writeLanMacKey("c:\\", "key.dll",CsjFileConst.ENCODE_UTF_8);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
System.out.println("REGEDIT ERROR");
}
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String getOneKeyUncode(boolean isPayMoney) throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String code = CsjDesEncrypt.encode(CsjProcess.s_local_inet_addr_with_line);
String limitDate = getKeyTValLine0();
String strDate = limitDate;
String strPre = "unpay";
if (isPayMoney) {
strPre = "payed";
}
String strMac = CsjProcess.s_local_inet_addr_with_line.replaceAll("-", "");
String strMac1 = strMac.substring(0, 6);
String strMac2 = strMac.substring(6, 12);
String str = CsjDesEncrypt.encode(strMac + CsjConst.SIGN_AT + strMac1
+ strPre + CsjConst.SIGN_AT + strMac2 + strDate
+ CsjConst.SIGN_AT + CmnRandomUtils.createRadomStrs(6, true, false));
return str;
}
/**
* @param isPayMoney
* @param code
* @return
* @throws Throwable
*/
public static String regeditKey(String mac, String strDate)
throws Throwable {
// System.out.println(CsjProcess.s_local_inet_addr + "<--");
String str = mac + "payed" + strDate + 000000;
str = CsjDesEncrypt.encode(str);
return str;
}
public static String getKeyTValLine0() throws Throwable {
String key = CmnFileUtils.getFileContent(
new File(s_file_key_T_file), IConstFile.ENCODE_UTF_8).get(0);
String unkey = CsjDesEncrypt.uncode(key);
return unLongStrKey(unkey);
}
public static void isAccessNet() throws Throwable {
if (isAccessNet) {
List<String> lst = CmnFileUtils.getFileContent(
new File(s_file_key_T_file), IConstFile.ENCODE_UTF_8);
if (lst.size()>1) {
isAccessNet = !lst.get(1).equals("NN");
}
}
}
public static String getKeyDateVal() throws Throwable {
return CsjDesEncrypt.uncode(CmnFileUtils.getFileContent(
new File(s_file_key_file), IConstFile.ENCODE_UTF_8).get(0));
}
/**
* @throws Throwable
*
*/
public static void writeLanMacKey() throws Throwable {
System.out.println("begin......");
CmnLanIPUtils ip = new CmnLanIPUtils();
List<String> list = ip.getLanIPArrayList();
List<String> macList = ip.getLanIPArrayList();
System.out.println("---------------- list ----------------");
Thread.sleep(5000);
for (String str : list) {
String mac = CsjMacAddress.run(str);
if (CmnStrUtils.isNotEmpty(mac) && mac.matches(RegConstStr.MAC)) {
String stepStr = CmnStrUtils.leftFillChar(
String.valueOf(step++), '0', 6);
String strDate = CsjCheck.limitDate + stepStr;
macList.add(CsjDesEncrypt.encode(mac)
+ CsjDesEncrypt.encode(strDate));
}
}
CmnFileUtils
.writeFile(proty, keyNm, IConstFile.ENCODE_UTF_8, macList);
System.out.println("最后有多少个===>" + list.size());
}
public ArrayList<String> getLanIPArrayList() {
ArrayList<String> arrayIP = null;
try {
InitSystem initSystem = null;
initSystem = new InitSystem();
Thread thread = new Thread(initSystem);
thread.start();
thread.join();
arrayIP = initSystem.getArrayIPUsed();
} catch (UnknownHostException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return arrayIP;
}
private class InitSystem implements Runnable {
private int firstIP = 2;// 查询的 IP 地址的最后一位起始点
private int lastIP = 255;// 查询的 IP 地址的最后一位结束点
private volatile ArrayList<Thread> arrayThread;// 子线程段
private final int MAXTHREADNUM = 30; // 最大同时进行的子线程数量
private int threadNumNow;// 当前正在进行的子线程数量
private volatile ArrayList<String> arrayIP;// 局域网查询所有可能的 IP 地址的结果集
private volatile ArrayList<String> arrayIPUsed;// 局域网查询已经使用的 IP 地址的结果集
private InitSystem(String ip) {
System.out.println("IP===>" + ip);
arrayIP = new ArrayList<String>();
arrayIPUsed = new ArrayList<String>();
arrayThread = new ArrayList<Thread>();
setIPAddressList(ip);
}
private InitSystem() throws UnknownHostException {
this(InetAddress.getLocalHost().getHostAddress());
}
private synchronized ArrayList<String> getArrayIPUsed() {
try {
System.out.println("getArrayIPUsed: arrayIP.size===>"
+ arrayIP.size());
while (arrayIP.size() > 0) {
Thread.sleep(300);
}
} catch (InterruptedException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return arrayIPUsed;
}
private void setIPAddressList(String ip) {
// 根据这个 ip 地址查询它所在的局域网的所有可能 IP 地址的集合
int lastPointIndex = ip.lastIndexOf('.');
String stringIPHead = ip.substring(0, ++lastPointIndex);
System.out.println("stringIPHead===>" + stringIPHead);
String stringIP = null;
for (int i = firstIP; i <= lastIP; i++) {
stringIP = stringIPHead + i;
arrayIP.add(stringIP);
}
System.out.println("进放到这里...arrayIP的总个数:" + arrayIP.size());
}
public void run() {
synchronized (this) {
try {
System.out.println("run() arrayIP.size()===>"
+ arrayIP.size());
System.out
.println("run() threadNumNow===>" + threadNumNow);
System.out.println("arrayThread.size()"
+ arrayThread.size());
while (arrayIP.size() > 0) {
while (threadNumNow >= MAXTHREADNUM) {
System.out.println("线程超出30,中止后面的...");
for (Thread thread : arrayThread) {
if (!thread.getState().equals(
Thread.State.TERMINATED)) {
thread.join(5);
}
--threadNumNow;
}
arrayThread = new ArrayList<Thread>();
}
Thread thread = new Thread(new InnerClass(arrayIP
.remove(0)));
thread.start();
threadNumNow++;
arrayThread.add(thread);
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
}
}
private class InnerClass implements Runnable {
// 线程查询一个 IP 是否是可以连接的 是则加入到相应的 IP 数组
private String ip;
private InnerClass(String ip) {
System.out.println("InnerClass ip===>" + ip);
this.ip = ip;
}
private boolean isUsedIPAddress(String ip) {
System.out.println("isUsedIPAddress===>" + ip);
synchronized (this) {
System.out.println("进入此地.....");
// 判断这个 IP 地址在当前局域网中是否是可连接的 IP
Process process = null;
BufferedReader bufReader = null;
String bufReadLineString = null;
try {
process = Runtime.getRuntime().exec(
"ping " + ip + " -w 100 -n 1");
bufReader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
for (int i = 0; i < 6 && bufReader != null; i++) {
bufReader.readLine();
}
bufReadLineString = bufReader.readLine();
System.out.println("bufReadLineString===>"
+ bufReadLineString);
if (bufReadLineString == null) {
process.destroy();
return false;
}
if (bufReadLineString.indexOf("timed out") > 0
|| bufReadLineString.length() < 17
|| bufReadLineString.indexOf("invalid") > 0) {
process.destroy();
return false;
}
} catch (IOException e) {
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
process.destroy();
return true;
}
}
public void run() {
synchronized (this) {
if (isUsedIPAddress(ip)) {
arrayIPUsed.add(ip);
}
}
}
}
}
}
//
// 利用IP地址获得局域网计算机的名字、mac地址、工作组
//
// System.out.println("192.168.1.187对应网卡的MAC是:");
//
// NetworkInterface
// ne=NetworkInterface.getByInetAddress(InetAddress.getByName("192.168.1.187"));
//
// byte[]mac=ne.getHardwareAddress();
//
// String mac_s=hexByte(mac[0])+":"+hexByte(mac[1])+":"+
// hexByte(mac[2])+":"+hexByte(mac[3])+":"+
// hexByte(mac[4])+":"+hexByte(mac[5]);System.out.println(mac_s);
//
// 程序运行结果: 192.168.1.187对应网卡的MAC是: 00:0c:f1:20:75:58
-------C:\aa\common\CmnLog.java
package org.mydbsee.common;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class CmnLog {
public static Logger logger = LogManager.getLogger(CmnLog.class.getName());
public static void main(String[] args) {
logger.debug("aaaaaaaaaaa");
}
}
-------C:\aa\common\CmnLog5j.java
/**
*
*/
package org.mydbsee.common;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.log.constant.CsjLogConst;
/**
* @author Think
*
*/
public class CmnLog5j {
public static BufferedWriter s_log5j = null;
public static void main(String[] args) {
try {
initLog5j("c:\\1\\","a.txt",IConstFile.ENCODE_UTF_8);
s_log5j.write("1111");
s_log5j.write("\r\n");
s_log5j.write("2222");
closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
public static void initLog5j(String logPath,String fileNm, String enCode) throws Throwable {
File file = new File(logPath);
file.mkdirs();
s_log5j = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logPath + fileNm), enCode));
}
public static void initLog5j(String filePath, String enCode) throws Throwable {
File file = new File(filePath);
s_log5j = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), enCode));
}
public static void closeLog5j() {
try {
if (s_log5j != null) {
s_log5j.close();
s_log5j=null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeLine(String str) {
CmnFileUtils.writeWithbBlank(s_log5j, str, 0);
}
public static void writeWithConsole(String str) {
CmnFileUtils.writeWithbBlank(s_log5j, str, 0);
System.out.println(str);
}
public static String getXlsPosLog(String filePath, String sheetNm, String row,String col, String content) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(filePath)) {
sb.append(CsjLogConst.SIGN_FILE_PATH + addlrBracketsM(filePath,true) );
}
if (CmnStrUtils.isNotEmpty(sheetNm)) {
sb.append(CsjLogConst.SIGN_SHEET_NM + addlrBracketsM(sheetNm,true) );
}
if (CmnStrUtils.isNotEmpty(row)) {
sb.append(CsjLogConst.SIGN_ROW + addlrBracketsM(row,true) );
}
if (CmnStrUtils.isNotEmpty(col)) {
sb.append(CsjLogConst.SIGN_COL + addlrBracketsM(col,true) );
}
if (CmnStrUtils.isNotEmpty(content)) {
sb.append(CsjLogConst.SIGN_CONTENT + addlrBracketsM(content,true) );
}
return addlrBracket_M_L_JP(sb.toString(),true);
}
public static String addlrBracketsM(String str,boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.SIGN_BRACKETS_M_L + str + CsjConst.SIGN_BRACKETS_M_R;
}
public static String addlrBracket_M_L_JP(String str, boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.Z_SIGN_BRACKETS_M_L_JP + str + CsjConst.Z_SIGN_BRACKETS_M_R_JP;
}
public static String addlrBracketsS(String str, boolean isBlankNotPrint) {
if (CmnStrUtils.isEmpty(str)) {
if (isBlankNotPrint) {
return "";
}
}
return CsjConst.SIGN_BRACKETS_S_L + str + CsjConst.SIGN_BRACKETS_S_R;
}
/**
* @param writer
* @param line
*/
public static void writeLine(BufferedWriter writer, String line) throws Throwable {
try {
writer.write(line);
writer.newLine();
writer.flush();
} catch (Throwable e) {
throw e;
}
}
/**
* @param writer
* @param line
*/
public static void writeLineWithConsole(BufferedWriter writer, String line) throws Throwable {
try {
writer.write(line);
writer.newLine();
writer.flush();
System.out.println(line);
} catch (Throwable e) {
throw e;
}
}
/**
* @param writer
* @throws IOException
*/
public static void close(BufferedWriter writer) throws Throwable {
// TODO Auto-generated method stub
try {
if (writer!=null) {
writer.close();
writer=null;
}
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnNumUtils.java
/**
*
*/
package org.mydbsee.common;
/**
* @author Think
*
*/
public class CmnNumUtils {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* support Numeric format:<br>
* "33" "+33" "033.30" "-.33" ".33" " 33." " 000.000 "
*
* @param str String
* @return boolean
*/
public static boolean isNumeric(String str) {
int begin = 0;
boolean once = true;
if (str == null || str.trim().equals("")) {
return false;
}
str = str.trim();
if (str.startsWith("+") || str.startsWith("-")) {
if (str.length() == 1) {
// "+" "-"
return false;
}
begin = 1;
}
for (int i = begin; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
if (str.charAt(i) == '.' && once) {
// '.' can only once
once = false;
} else {
return false;
}
}
}
if (str.length() == (begin + 1) && !once) {
// "." "+." "-."
return false;
}
return true;
}
/**
* support Integer format:<br>
* "33" "003300" "+33" " -0000 "
*
* @param str String
* @return boolean
*/
public static boolean isInteger(String str) {
int begin = 0;
if (str == null || str.trim().equals("")) {
return false;
}
str = str.trim();
if (str.startsWith("+") || str.startsWith("-")) {
if (str.length() == 1) {
// "+" "-"
return false;
}
begin = 1;
}
for (int i = begin; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* use Exception
* support Numeric format:<br>
* "33" "+33" "033.30" "-.33" ".33" " 33." " 000.000 "
*
* @param str String
* @return boolean
*/
public static boolean isNumericEx(String str) {
try {
Double.parseDouble(str);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
/**
* use Exception
* support less than 11 digits(<11)<br>
* support Integer format:<br>
* "33" "003300" "+33" " -0000 " "+ 000"
*
* @param str String
* @return boolean
*/
public static boolean isIntegerEx(String str) {
str = str.trim();
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException ex) {
if (str.startsWith("+")) {
return isIntegerEx(str.substring(1));
}
return false;
}
}
// 判断是否是整数
public static boolean isNumericReg(String s) {
if (CmnStrUtils.isNotEmpty(s))
return s.matches("^[0-9]*$");
else
return false;
}
// 判断传递来的是否是数字
public static int checkID(String s) {
if ((s == null) || (s.length() == 0) || !s.matches("^[0-9]*$")) {
return 0;
} else {
if (s.length() < 10) {
return Integer.parseInt(s);
} else {
return 0;
}
}
}
// 判断传递来的是否是字符串
public static String checkString(String s) {
if ((s == null) || (s.length() == 0) || s.matches("^[0-9]*$")) {
return "";
} else {
return s;
}
}
}
-------C:\aa\common\CmnPoiUtils.java
package org.mydbsee.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import jp.co.csj.tools.utils.common.CsjPath;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.db.core.XlsTblPara;
import jp.co.csj.tools.utils.msg.dbtools.CsjDbToolsMsg;
import jp.co.csj.tools.utils.poi.core.CsjCellInfo;
import jp.co.csj.tools.utils.poi.core.CsjColInfo;
import jp.co.csj.tools.utils.poi.core.CsjDbCellStyle;
import jp.co.csj.tools.utils.poi.core.CsjPatr;
import jp.co.csj.tools.utils.poi.core.CsjPosition;
import jp.co.csj.tools.utils.poi.core.CsjRowInfo;
import jp.co.csj.tools.utils.poi.core.CsjSchedual;
import jp.co.csj.tools.utils.poi.core.CsjSheetInfo;
import jp.co.csj.tools.utils.reg.RegConstStr;
public class CmnPoiUtils {
public static final int S_CELL_MAX_NUM_2007 = 1048576;
public static final int S_CELL_MAX_NUM_2003 = 32767;
/**
* Remove a row by its index
* @param sheet a Excel sheet
* @param rowIndex a 0 based index of removing row
* @throws Throwable
*/
public static void removeRow(Sheet sheet, int rowIndex) throws Throwable {
try {
int lastRowNum=sheet.getLastRowNum();
if(rowIndex>=0&&rowIndex<lastRowNum)
sheet.shiftRows(rowIndex+1,lastRowNum,-1);//将行号为rowIndex+1一直到行号为lastRowNum的单元格全部上移一行,以便删除rowIndex行
if(rowIndex==lastRowNum){
Row removingRow=sheet.getRow(rowIndex);
if(removingRow!=null)
sheet.removeRow(removingRow);
}
} catch (Throwable e) {
throw e;
}
}
public static void insertRow(Sheet sheet, int starRow, int rows,boolean isWithContent) throws Throwable {
try {
if (rows <= 0) {
return;
}
if (starRow + 1 == sheet.getLastRowNum()) {
CmnPoiUtils.setCellValue(sheet, starRow + 2, 0, " ");
}
// 选择一个区域,从startRow+1直到最后一行
sheet.shiftRows(starRow + 1, sheet.getLastRowNum(), rows, true, false);
starRow = starRow - 1;
for (int i = 0; i < rows; i++) {
Row sourceRow = null;
Row targetRow = null;
Cell sourceCell = null;
Cell targetCell = null;
int m;
starRow = starRow + 1;
sourceRow = sheet.getRow(starRow);
if (sourceRow == null) {
sourceRow = sheet.createRow(starRow);
}
// 從start創建新的一行
targetRow = sheet.createRow(starRow + 1);
targetRow.setHeight(sourceRow.getHeight());
// 处理刚刚创建的一行
for (m = sourceRow.getFirstCellNum(); m < sourceRow.getLastCellNum(); m++) {
sourceCell = sourceRow.getCell(m);
targetCell = targetRow.createCell(m);
if (sourceCell!=null &&targetCell!=null) {
// 风格一样
targetCell.setCellStyle(sourceCell.getCellStyle());
targetCell.setCellType(sourceCell.getCellType());
if (isWithContent) {
targetCell.setCellValue(getCellStr(sourceCell));
}
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, String str, CellStyle cs) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (cs != null) {
cell.setCellStyle(cs);
cell.setCellValue(str);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, String str, CellStyle cs, CellStyle csBlank) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (CmnStrUtils.isEmpty(str)) {
cell.setCellStyle(csBlank);
} else {
cell.setCellStyle(cs);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, XlsTblPara xlsTblPara, CsjDbCellStyle cellStyle) throws Throwable {
Cell cell = null;
try {
if (CmnStrUtils.isEmpty(xlsTblPara.getParaVal())) {
cell = setCellValue(sheet, rowPos, colNum, xlsTblPara.getParaVal());
cell.setCellStyle(cellStyle.getCsRecordBlank());
} else {
cell = setCellValue(sheet, rowPos, colNum, xlsTblPara.getParaVal());
cell.setCellStyle(cellStyle.getCsRecordStr());
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValueWithCs(Sheet sheet, int rowPos, int colNum, RichTextString str,
CellStyle cs) throws Throwable {
Cell cell = null;
try {
cell = setCellValue(sheet, rowPos, colNum, str);
if (cell != null) {
cell.setCellStyle(cs);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValue(Sheet sheet, int rowNum, int colNum, RichTextString val) throws Throwable {
Cell cell = null;
try {
cell = getOrCreateCell(sheet, rowNum, colNum);
if (CmnStrUtils.isNotEmpty(val) && getExcelMaxRowNum(sheet) < val.length()) {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000088));
}
if (cell != null) {
cell.setCellValue(val);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static Cell setCellValue(Sheet sheet, int rowNum, int colNum, String val) throws Throwable {
Cell cell = null;
try {
cell = getOrCreateCell(sheet, rowNum, colNum);
if (CmnStrUtils.isNotEmpty(val) && getExcelMaxRowNum(sheet) < val.length()) {
throw new Exception(CsjDbToolsMsg.coreMsgMap.get(CsjDbToolsMsg.MSG_I_0000088));
}
if (cell != null) {
cell.setCellValue(val);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
private static int getExcelMaxRowNum(Sheet sheet) throws Throwable{
int maxRow = 0;
try {
if (sheet instanceof HSSFSheet) {
maxRow = S_CELL_MAX_NUM_2003;
} else {
maxRow = S_CELL_MAX_NUM_2007;
}
} catch (Throwable e) {
throw e;
}
return maxRow;
}
/**
* @param sheet
* @param rowNum
* @param colNum
* @return
*/
public static Cell getOrCreateCell(Sheet sheet, int rowNum, int colNum) throws Throwable {
Cell cell = null;
try {
if (sheet == null) {
return null;
}
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
cell = row.getCell(colNum);
if (cell == null) {
cell = row.createCell(colNum);
}
} catch (Throwable e) {
throw e;
}
return cell;
}
public static List<String>
getCellContents(File inFile, String fromSheetName) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
String str = CsjConst.EMPTY;
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
fileInputStream.close();
printSheet(inFile.getAbsolutePath(), sheet);
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(File inFile,
String fromSheetName, int rowNum) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
String str = CsjConst.EMPTY;
for (Row row : sheet) {
if (row.getRowNum() == rowNum) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
}
fileInputStream.close();
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(str);
}
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, int colBegin,boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
if (cell.getColumnIndex()<colBegin) {
continue;
}
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retList.add(str);
}
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static CsjCellInfo getCellFontByContent(Row row, String str,boolean checkStrikeOut) throws Throwable {
CsjCellInfo cellInfo =null;
try {
if (row != null) {
for (Cell cell : row) {
if (str.equals(getCellContent(cell, checkStrikeOut))) {
cellInfo = getCellInfo(cell);
break;
}
}
}
} catch (Throwable e) {
throw e;
}
return cellInfo;
}
public static Font createCellFont(Workbook wb, CsjCellInfo cellInfo) {
Font ft = wb.createFont();
Font f = cellInfo.getFont();
ft.setBold(f.getBold());
ft.setBoldweight(f.getBoldweight());
ft.setCharSet(f.getCharSet());
ft.setColor(f.getColor());
ft.setFontHeight(f.getFontHeight());
ft.setFontHeightInPoints(f.getFontHeightInPoints());
ft.setFontName(f.getFontName());
ft.setItalic(f.getItalic());
ft.setStrikeout(f.getStrikeout());
ft.setTypeOffset(f.getTypeOffset());
ft.setUnderline(f.getUnderline());
return ft;
}
public static CellStyle createCellStyle(Workbook wb,CsjCellInfo cellInfo) {
CellStyle retCs = wb.createCellStyle();
if (cellInfo == null) {
return null;
}
CellStyle cs =cellInfo.getCs();
if (cs == null) {
return null;
}
retCs.setAlignment(cs.getAlignment());
retCs.setBorderBottom(cs.getBorderBottom());
retCs.setBorderLeft(cs.getBorderLeft());
retCs.setBorderRight(cs.getBorderRight());
retCs.setBorderTop(cs.getBorderTop());
retCs.setBottomBorderColor(cs.getBottomBorderColor());
retCs.setDataFormat(cs.getDataFormat());
retCs.setFillBackgroundColor(cs.getFillBackgroundColor());
retCs.setFillForegroundColor(cs.getFillForegroundColor());
retCs.setFillPattern(cs.getFillPattern());
retCs.setFont(createCellFont(wb, cellInfo));
retCs.setHidden(cs.getHidden());
retCs.setIndention(cs.getIndention());
retCs.setLeftBorderColor(cs.getLeftBorderColor());
retCs.setLocked(cs.getLocked());
retCs.setRightBorderColor(cs.getRightBorderColor());
retCs.setRotation(cs.getRotation());
retCs.setShrinkToFit(cs.getShrinkToFit());
retCs.setTopBorderColor(cs.getTopBorderColor());
retCs.setVerticalAlignment(cs.getVerticalAlignment());
retCs.setWrapText(cs.getWrapText());
// if (cell instanceof HSSFCell) {
// HSSFCell c = (HSSFCell)cell;
// font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
// } else {
// XSSFCell c = (XSSFCell)cell;
// font = c.getCellStyle().getFont();
// }
//
// Font font = ((HSSFCellStyle)retCs).getFont((HSSFWorkbook)wb);
// font.getBold();
return retCs;
}
public static void testgetCellContents(File inFile, String fromSheetName,
int rowNum) throws Throwable {
try {
Workbook wb;
FileInputStream fileInputStream = new FileInputStream(inFile);
if (CmnStrUtils.isEndByIgnor(inFile.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(fromSheetName);
removeRow(sheet, rowNum);
fileInputStream.close();
FileOutputStream fileOut = new FileOutputStream("d:\\aaa1.xls");
wb.write(fileOut);
fileOut.close();
} catch (Throwable e) {
throw e;
}
}
public static LinkedHashMap<Integer,String> getCellContentMaps(Row row, boolean checkStrikeOut) throws Throwable {
LinkedHashMap<Integer,String> map = new LinkedHashMap<Integer, String>();
try {
if (row != null) {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
map.put(cell.getRowIndex(), str);
}
}
}
} catch (Throwable e) {
throw e;
}
return map;
}
public static List<String> getCellContents(Sheet sheet, int col, int rowMin,int rowMax, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Row row: sheet) {
int rowNum = row.getRowNum();
if (rowMin<=rowNum&& rowNum<=rowMax) {
str = getCellContent(row, col, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static List<String> getCellContents(Row row, int preCol, int endCol, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
int cellCol = cell.getColumnIndex();
if (preCol <= cellCol && cellCol <= endCol) {
str = getCellContent( cell, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
throw e;
}
return retList;
}
public static LinkedHashMap<String,String> getCellContentsMap(Row row, boolean checkStrikeOut) throws Throwable {
LinkedHashMap<String,String> retMap = new LinkedHashMap<String,String>();
try {
String str = CsjConst.EMPTY;
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
retMap.put(String.valueOf(cell.getColumnIndex()), str);
}
}
} catch (Throwable e) {
throw e;
}
return retMap;
}
public static String getCellContent(Row row, int colIndex, boolean checkStrikeOut) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (row == null) {
return CsjConst.EMPTY;
}
Cell cell = row.getCell(colIndex);
if(cell == null) {
return CsjConst.EMPTY;
}
retStr = getCellContent(cell, checkStrikeOut);
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static List<String> getCellContents(Sheet sheet, boolean checkStrikeOut) {
List<String> retList = new ArrayList<String>();
try {
String str = CsjConst.EMPTY;
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, checkStrikeOut);
retList.add(str);
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retList;
}
public static void clearCellContents(Sheet sheet,int rowMin,int rowMax,int colMin,int colMax) {
try {
for (Row row : sheet) {
if (row.getRowNum()<=rowMin||(rowMax>=0 && row.getRowNum()>=rowMax)) {
continue;
}
for (Cell cell : row) {
if (cell.getColumnIndex()<=colMin||(colMax>=0 && cell.getColumnIndex()>=colMax)) {
continue;
}
cell.setCellValue("");
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
}
public static HashSet<String> getCellContentsMap(String filePath, String sheetNm,boolean checkStrikeOut)throws Throwable {
return getCellContentsMap(new File(filePath),sheetNm,checkStrikeOut);
}
public static HashSet<String> getCellContentsMap(File f, String sheetNm, boolean checkStrikeOut)throws Throwable {
HashSet<String> sSet = new HashSet<String>();
try {
Workbook wb;
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
String str = CsjConst.EMPTY;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
if (CmnStrUtils.isNotEmpty(sheetNm)) {
if (sheet.getSheetName().equals(sheetNm) == false) {
continue;
}
}
for (Row row : sheet) {
for (Cell cell : row) {
str = CmnStrUtils.lrTrimSpace(getCellContent( cell, false));
if (CmnStrUtils.isNotEmpty(str)) {
sSet.add(CmnStrUtils.toLowOrUpStr(str));
}
}
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
return sSet;
}
public static List<String> getCellContents(String filePath, boolean checkStrikeOut) throws Throwable {
List<String> retList = new ArrayList<String>();
try {
File f = new File(filePath);
if (f.isFile() == false) {
return retList;
}
FileInputStream fs = new FileInputStream(f);
Workbook wb ;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
String str = CsjConst.EMPTY;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
for (Row row : sheet) {
for (Cell cell : row) {
str = getCellContent( cell, false);
retList.add(str);
}
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
return retList;
}
public static String getCellContent(Sheet sheet, int rowIndex, int colIndex, boolean checkStrikeOut) throws Throwable {
String retVal = CsjConst.EMPTY;
try {
if (sheet != null) {
Row row = sheet.getRow(rowIndex);
retVal = getCellContent(row, colIndex, checkStrikeOut);
}
} catch (Throwable e) {
throw e;
}
return retVal;
}
public static String getCellContent(String fileAbsPath,String sheetNm, int rowIndex, int colIndex, boolean checkStrikeOut) throws Throwable {
FileInputStream fileIn = null;
Workbook wb;
try {
fileIn = new FileInputStream(new File(fileAbsPath));
if (CmnStrUtils.isEndByIgnor(fileAbsPath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileIn);
} else {
wb = new XSSFWorkbook(fileIn);
}
} catch (Throwable e) {
throw e;
} finally {
if (fileIn != null) {
fileIn.close();
}
}
return getCellContent(wb.getSheet(sheetNm),rowIndex, colIndex, checkStrikeOut);
}
public static String getCellAreaContents(Sheet sheet, int rowBeginIndex, int rowEndIndex, int colBeginIndex,
int colEndIndex, List<String> strList, boolean checkStrikeOut) {
StringBuffer retSb = new StringBuffer();
try {
for (Row row : sheet) {
if (rowBeginIndex <= row.getRowNum() && row.getRowNum() <= rowEndIndex) {
for (Cell cell : row) {
if (colBeginIndex <= cell.getColumnIndex() && cell.getColumnIndex() <= colEndIndex) {
String val = getCellContent( cell, checkStrikeOut);
retSb.append(val);
strList.add(val);
}
}
}
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return retSb.toString();
}
public static String getCellContent(Cell cell, boolean checkStrikeOut) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (null == cell) {
return retStr;
}
if (checkStrikeOut) {
Font font;
if (cell instanceof HSSFCell) {
HSSFCell c = (HSSFCell)cell;
font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
if (font.getStrikeout()) {
return retStr;
}
} else if (cell instanceof XSSFCell) {
XSSFCell c = (XSSFCell)cell;
font = c.getCellStyle().getFont();
if (font.getStrikeout()) {
return retStr;
}
// XSSFRichTextString richTextStr = c.getRichStringCellValue();
//
// StringBuffer sb = new StringBuffer();
// char ch[] = richTextStr.getString().toCharArray();
// for (int i = 0; i < richTextStr.length(); i++) {
// font = richTextStr.getFontAtIndex(i);
// if (font != null && font.getStrikeout()) {
//
// } else {
// sb.append(ch[i]);
// }
// }
// retStr = sb.toString();
// return retStr;
}
}
retStr = getCellStr(cell);
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static CsjCellInfo getCellInfo(Cell cell) throws Throwable {
if (null == cell) {
return null;
}
CsjCellInfo retVal = null;
try {
retVal = new CsjCellInfo(getCellStr(cell),cell.getRowIndex(),cell.getColumnIndex());
Font font = null;
if (cell instanceof HSSFCell) {
HSSFCell c = (HSSFCell)cell;
font = c.getCellStyle().getFont(c.getRow().getSheet().getWorkbook());
} else {
XSSFCell c = (XSSFCell)cell;
font = c.getCellStyle().getFont();
}
CellStyle cs = cell.getCellStyle();
retVal.setCs(cs);
retVal.setFont(font);
} catch (Throwable e) {
throw e;
}
return retVal;
}
/**
* @param cell
* @param retStr
* @return
* @throws Throwable
*/
private static String getCellStr(Cell cell) throws Throwable {
String retStr = "";
try {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
retStr = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} else {
retStr = String.valueOf(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
retStr = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
try {
if (DateUtil.isCellDateFormatted(cell)) {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} else {
retStr = String.valueOf(cell.getNumericCellValue());
retStr = CmnStrUtils.getNumberByTrimDot0(retStr);
}
} catch (Throwable e) {
CmnLog.logger.info(e.getMessage());
try {
retStr = cell.getRichStringCellValue().getString();
} catch (Throwable e1) {
CmnLog.logger.info(e1.getMessage());
try {
retStr = CmnDateUtil.getFormatDateTime(cell.getDateCellValue(), CsjConst.YYYY_MM_DD_SLASH);
} catch (Throwable e2) {
retStr = cell.getCellFormula();
CmnLog.logger.info(e2.getMessage());
}
}
}
break;
default:
// System.out.println();
}
} catch (Throwable e) {
throw e;
}
return retStr;
}
public static void setCellComment(Cell cell, RichTextString content, String author) throws Throwable {
try {
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
Drawing patr = cell.getSheet().createDrawingPatriarch();
//anchor defines size and position of the comment in worksheet
Comment comment = null;
if (cell instanceof HSSFCell) {
comment = patr.createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
// set text in the comment
comment.setString(content);
} else if (cell instanceof XSSFCell) {
comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 6, 5));
XSSFRichTextString xssfRichTextString = new XSSFRichTextString(content.getString());
comment.setString(xssfRichTextString);
}
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell
comment.setAuthor(author);
// The first way to assign comment to a cell is via XSSFCell.setCellComment method
cell.setCellComment(comment);
} catch (Throwable e) {
throw e;
}
}
public static void setCellCommentBig(Cell cell, RichTextString content, String author) throws Throwable {
try {
// Create the drawing patriarch. This is the top level container for all shapes including cell comments.
Drawing patr = cell.getSheet().createDrawingPatriarch();
//anchor defines size and position of the comment in worksheet
Comment comment = null;
if (cell instanceof HSSFCell) {
comment = patr.createCellComment(new HSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 8, 17));
// set text in the comment
comment.setString(content);
} else if (cell instanceof XSSFCell) {
comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short)4, 2, (short) 8, 17));
XSSFRichTextString xssfRichTextString = new XSSFRichTextString(content.getString());
comment.setString(xssfRichTextString);
}
//set comment author.
//you can see it in the status bar when moving mouse over the commented cell
comment.setAuthor(author);
// The first way to assign comment to a cell is via XSSFCell.setCellComment method
cell.setCellComment(comment);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param csjPart
* @throws Throwable
*/
public static void setCommentByCell(Cell cell, String content, Font font, CsjPatr csjPart,
boolean isVisable, String user) throws Throwable {
// Create the drawing patriarch. This is the top level container for all
// shapes including cell comments.
try {
Comment comment = null;
RichTextString string;
if (cell instanceof HSSFCell) {
comment = csjPart.getPatr().createCellComment(
new HSSFClientAnchor(0, 0, 0, 0, csjPart.getCol1(), csjPart.getRow1(), csjPart.getCol2(), csjPart
.getRow2()));
string = new HSSFRichTextString(content);
string.applyFont(font);
comment.setString(string);
} else if (cell instanceof XSSFCell) {
comment = csjPart.getPatr().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, csjPart.getCol1(), csjPart.getRow1(), csjPart.getCol2(), csjPart
.getRow2()));
string = new XSSFRichTextString(content);
string.applyFont(font);
comment.setString(string);
}
// modify background color of the comment
//comment.setFillColor(204, 236, 255);
comment.setVisible(isVisable); // by default comments are hidden. This
// one is always visible.
if (CmnStrUtils.isNotEmpty(user)) {
comment.setAuthor(user);
}
/**
* The second way to assign comment to a cell is to implicitly specify
* its row and column. Note, it is possible to set row and column of a
* non-existing cell. It works, the comment is visible.
*/
comment.setRow(cell.getRowIndex());
comment.setColumn(cell.getColumnIndex());
} catch (Throwable e) {
throw e;
}
}
public static void setColorForDif(RichTextString oldRichStr,
RichTextString newRichStr, Font sFontRed, String enCode) {
String oldStr = oldRichStr.getString();
String newStr = newRichStr.getString();
List<CsjPosition> oldPositionList = new ArrayList<CsjPosition>();
List<CsjPosition> newPositionList = new ArrayList<CsjPosition>();
try {
byte[] oldByteArr = oldStr.getBytes(enCode);
byte[] newByteArr = newStr.getBytes(enCode);
int oldLen = oldStr.length();//oldByteArr.length;
int newLen = newStr.length();//ByteArr.length;
int minLen = oldLen<newLen? oldLen : newLen;
for (int i = 0; i < minLen; i++) {
if (oldStr.charAt(i) != newStr.charAt(i)) {
oldPositionList.add(new CsjPosition(i, i+1));
newPositionList.add(new CsjPosition(i, i+1));
}
}
if (minLen < oldLen) {
oldPositionList.add(new CsjPosition(minLen, oldLen));
} else if (minLen < newLen) {
newPositionList.add(new CsjPosition(minLen, newLen));
}
for (CsjPosition pos : oldPositionList) {
oldRichStr.applyFont(pos.getStartPos(), pos.getEndPos(), sFontRed);
}
for (CsjPosition pos : newPositionList) {
newRichStr.applyFont(pos.getStartPos(), pos.getEndPos(), sFontRed);
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
System.out.println("csj:color can't use!");
}
}
/*
* /**
*
* @param logger
*
* @param sheet
*/
public static void printSheet(String path, Sheet sheet) throws Throwable {
try {
for (Row row : sheet) {
for (Cell cell : row) {
String val = getCellContent((Cell) cell, true);
if (CmnStrUtils.isNotEmpty(val)) {
CmnLog.logger.error("file path:["+path+"]sheet:["+sheet.getSheetName()+"]row:[" + row.getRowNum() + "]col:[" + cell.getColumnIndex() + "]val:["
+ getCellContent( cell, true) + "]");
}
}
}
} catch (Throwable e) {
throw e;
}
}
public static void printSheet(String filePath) throws Throwable {
try {
File f = new File(filePath);
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.toLowOrUpStr(filePath).endsWith(CmnStrUtils.toLowOrUpStr(CsjConst.EXCEL_DOT_XLS_1997))) {
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
printSheet(f.getAbsolutePath(),wb.getSheetAt(i));
}
} else if (CmnStrUtils.toLowOrUpStr(filePath).endsWith(CmnStrUtils.toLowOrUpStr(CsjConst.EXCEL_DOT_XLSX_2007))) {
XSSFWorkbook wb = new XSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
printSheet(f.getAbsolutePath(),wb.getSheetAt(i));
}
}
fs.close();
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetWithOutNms(Workbook wb, Set<String> sheetNmSet) throws Throwable {
try {
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (sheetNmSet.contains(snm)) {
continue;
}
set.add(snm);
}
deleteSheetNm(wb, set);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetWithOutNm(Workbook wb, String sheetNm) throws Throwable {
try {
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (sheetNm.equals(snm)) {
continue;
}
set.add(snm);
}
deleteSheetNm(wb, set);
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteSheetNm(Workbook wb, HashSet<String> set) throws Throwable {
try {
Iterator iterator = set.iterator();
while(iterator.hasNext()){
String sheetNm = iterator.next().toString();
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (snm.equals(sheetNm)) {
wb.removeSheetAt(i);
break;
}
}
}
} catch (Throwable e) {
throw e;
}
}
/**
* @param wb
* @param map
* @throws Throwable
*/
public static void deleteWithOutSheetNm(Workbook wb, HashSet<String> set) throws Throwable {
try {
HashSet<String> deleteSheetNmSet = new HashSet<String>();
for (int i = 0; i <wb.getNumberOfSheets(); i++) {
String sheetNm = wb.getSheetAt(i).getSheetName();
if (!set.contains(sheetNm)) {
deleteSheetNmSet.add(sheetNm);
}
}
deleteSheetNm(wb, deleteSheetNmSet);
} catch (Throwable e) {
throw e;
}
}
/**
* @param cell
* @return
* @throws Throwable
*/
public static String getCellComment(Cell cell) throws Throwable {
String retStr = CsjConst.EMPTY;
try {
if (cell == null || cell.getCellComment() == null || cell.getCellComment().getString() == null) {
} else {
retStr = cell.getCellComment().getString().getString();
}
} catch (Throwable e) {
throw e;
}
return retStr;
}
/**
* @param xlsPath
* @return
* @throws Throwable
* @throws IOException
* @throws FileNotFoundException
*/
public static List<String> getSheetNms(String xlsPath,
List<String> sheetList) throws Throwable {
Workbook wb = null;
FileInputStream fs = null;
try {
File f = new File(xlsPath);
fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(xlsPath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
int sheetSum = wb.getNumberOfSheets();
for (int i = 0; i < sheetSum; i++) {
Sheet sheet = wb.getSheetAt(i);
sheetList.add(sheet.getSheetName());
}
wb.close();
fs.close();
} catch (Throwable e) {
throw e;
}
return sheetList;
}
/**
* @param xlsPath
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static void getSheetNmsAndFiles(String xlsPath,HashSet<String> sheetSet, HashMap<String,Sheet> sheetMap) throws Throwable {
Workbook wb;
LinkedList<File> tFileList = CmnFileUtils.getExcelFileByAbsPath(xlsPath, true);
for (File f : tFileList) {
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(), CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
int sheetSum = wb.getNumberOfSheets();
for (int i = 0; i < sheetSum; i++) {
Sheet sheet = wb.getSheetAt(i);
sheetMap.put(CmnStrUtils.toLowOrUpStr(sheet.getSheetName()), sheet);
sheetSet.add(CmnStrUtils.toLowOrUpStr(sheet.getSheetName()));
}
fs.close();
}
}
/**
* @param wb
* @param map
*/
public static void deleteSheetByNm(Workbook wb, HashSet<String> set, boolean isDelSheetNmInSet) {
for (String sheetNm : set) {
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
String snm = sheet.getSheetName();
if (isDelSheetNmInSet) {
if (snm.equals(sheetNm)) {
wb.removeSheetAt(i);
break;
}
} else {
if (snm.equals(sheetNm) == false) {
wb.removeSheetAt(i);
break;
}
}
}
}
}
public static void getXlsSheetsToOneXls(String filePath,String xlsNmPath,String xlsNm) throws Throwable {
LinkedList<File> fileList = CmnFileUtils.getFilesListReg(filePath, true,RegConstStr.EXCEL_REG_DOT);
FileInputStream fileIn = new FileInputStream(CsjPath.s_file_table_temp);
XSSFWorkbook wbOut = new XSSFWorkbook(fileIn);
Workbook wb;
for (File f : fileList) {
FileInputStream fs = new FileInputStream(f);
if (CmnStrUtils.isEndByIgnor(f.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fs);
} else {
wb = new XSSFWorkbook(fs);
}
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet fromSheet = wb.getSheetAt(i);
String toSheetNm = fromSheet.getSheetName();
Sheet toSheet = wbOut.createSheet(toSheetNm);
// copySheet(fromSheet, toSheet);
}
fs.close();
}
fileIn.close();
writeXls(wbOut,xlsNmPath,xlsNm);
}
public static Workbook getWorkBook(String filePath) throws Throwable {
File f = new File(filePath);
FileInputStream fileIn = new FileInputStream(f);
Workbook wb;
if (CmnStrUtils.isEndByIgnor(f.getName(),CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileIn);
} else {
wb = new XSSFWorkbook(fileIn);
}
return wb;
}
public static void writeXls(Workbook wb,String xlsNmPath,String xlsNm) throws Throwable {
FileOutputStream fileOut = null;
File f = new File(xlsNmPath);
f.mkdirs();
String filePath = xlsNmPath+ xlsNm+ CsjConst.EXCEL_DOT_XLSX_2007;
fileOut = new FileOutputStream(filePath);
wb.write(fileOut);
fileOut.close();
}
public static void main(String[] args) {
try {
// FileInputStream fileInputStream = new FileInputStream(new File("C:\\Users\\Think\\Desktop\\日本人姓氏大全集.xls"));
// XSSFWorkbook wb = new XSSFWorkbook(fileInputStream);
Workbook wb = getWorkBook("D:\\IDE\\eclipse-jee-oxygen-M4-win32\\eclipse\\workspace\\CsjToolsPic\\dbInfo\\template\\TableStructTemp.xlsx");
Sheet st = wb.getSheetAt(0);
for (Row row : st) {
for (Cell cell : row) {
System.out.println(getCellContent(cell, true));
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public static CsjSheetInfo getSheetContents(String filePath,String sheetNm,boolean checkStrikeOut) throws Throwable {
CsjSheetInfo csjSheetInfo =new CsjSheetInfo();
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
} else {
wb = new XSSFWorkbook(fileInputStream);
Sheet sheet = wb.getSheet(sheetNm);
csjSheetInfo =getSheetContents(sheet,checkStrikeOut);
}
csjSheetInfo.setFilePath(filePath);
fileInputStream.close();
return csjSheetInfo;
}
public static List<List<String>> getSchedualContents(String filePath,String sheetNm,boolean checkStrikeOut) throws Throwable {
List<List<String>> retLst = new ArrayList<List<String>>();
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
} else {
wb = new XSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(sheetNm);
for (Row row:sheet) {
List<String> strLst = new ArrayList<String>();
for (Cell cell : row) {
strLst.add(getCellContent(cell, false));
}
retLst.add(strLst);
}
fileInputStream.close();
return retLst;
}
public static void schedualXlsReplace(String filePath,String fileOutPath,String sheetNm,List<List<String>> strLst) throws Throwable{
try {
File file = new File(filePath);
FileInputStream fileIn = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(fileIn);
for (int i = wb.getNumberOfSheets()-1; i >=0 ; i--) {
wb.removeSheetAt(i);
}
wb.createSheet(sheetNm);
Sheet st = wb.getSheet(sheetNm);
for (int i = 0; i < strLst.size(); i++) {
List<String> lst = strLst.get(i);
for (int j = 0; j < lst.size(); j++) {
setCellValue(st, i, j, lst.get(j));
}
}
FileOutputStream fileOut = new FileOutputStream(fileOutPath);
wb.write(fileOut);
fileOut.close();
fileIn.close();
} catch (Throwable e) {
throw e;
}
}
public static Map<Integer,String> getSheetContents(String filePath,String sheetNm,int col,int rowStart,int rowEnd) throws Throwable {
Map<Integer,String> retMap = new HashMap<Integer, String>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath,CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
Sheet sheet = wb.getSheet(sheetNm);
for (int i = rowStart; i <=rowEnd; i++) {
Row row = sheet.getRow(i);
retMap.put(i-rowStart, getCellContent(row, col, false));
}
fileInputStream.close();
return retMap;
}
public static Map<String, TreeMap<String,CsjSchedual>> getScheduals(String filePath, String sheetName)throws Throwable {
Map<String, TreeMap<String,CsjSchedual>> hashMap = new LinkedHashMap<String, TreeMap<String,CsjSchedual>>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet st = wb.getSheetAt(i);
if (CmnStrUtils.isNotEmpty(sheetName)&& st.getSheetName().equals(sheetName) == false) {
continue;
}
String sheetNameCurrent = st.getSheetName();
TreeMap<String,CsjSchedual> treeMap = new TreeMap<String, CsjSchedual>();
for (Row row : st) {
if (row.getRowNum()<2) {
continue;
}
CsjSchedual schedual = new CsjSchedual();
schedual.setNo(getCellContent(row, 1, false));
schedual.setRunType(getCellContent(row, 2, false));
schedual.setWaitSecond(getCellContent(row, 3, false));
schedual.setRunFile(getCellContent(row, 4, false));
// -------------
schedual.setFromFolder(getCellContent(row, 5, false));
schedual.setFromFile(getCellContent(row, 6, false));
schedual.setToFolder(getCellContent(row, 7, false));
schedual.setToFile(getCellContent(row, 8, false));
schedual.setDbInExcelPath(getCellContent(row, 9, false));
schedual.setDbInSheet(getCellContent(row, 10, false));
schedual.setDbInTblNm(getCellContent(row, 11, false));
schedual.setDbInIsContain(getCellContent(row, 12, false));
schedual.setDbInResultPath(getCellContent(row, 13, false));
// -------------
schedual.setSyncExcelPath(getCellContent(row, 14, false));
schedual.setSyncExcelSheet(getCellContent(row, 15, false));
// -------------
schedual.setDbOutAllTableOneSheet(getCellContent(row, 16, false));
schedual.setDbOutAllTableResultPath(getCellContent(row, 17, false));
// -------------
schedual.setDbOutOneTableNm(getCellContent(row, 18, false));
schedual.setDbOutOneTableColNm(getCellContent(row, 19, false));
schedual.setDbOutOneTableColCharLike(getCellContent(row, 20, false));
schedual.setDbOutOneTableColNumMin(getCellContent(row, 21, false));
schedual.setDbOutOneTableColNumMax(getCellContent(row, 22, false));
schedual.setDbOutOneTableColDateMin(getCellContent(row, 23, false));
schedual.setDbOutOneTableColDateMax(getCellContent(row, 24, false));
schedual.setDbOutOneTableResultPath(getCellContent(row, 25, false));
// -------------
schedual.setDbOutSqlType(getCellContent(row, 26, false));
schedual.setDbOutSqlPath(getCellContent(row, 27, false));
schedual.setDbOutSqlResultPath(getCellContent(row, 28, false));
schedual.setDbOutConfigPath(getCellContent(row, 29, false));
schedual.setDbOutConfigResultPath(getCellContent(row, 30, false));
// -------------
schedual.setCompareStructOldPath(getCellContent(row, 31, false));
schedual.setCompareStructNewPath(getCellContent(row, 32, false));
schedual.setCompareStructResultPath(getCellContent(row, 33, false));
// -------------
schedual.setCompareDataPath(getCellContent(row, 34, false));
schedual.setCompareDataType(getCellContent(row, 35, false));
schedual.setCompareDbOut(getCellContent(row, 36, false));
schedual.setCompareOnlyChange(getCellContent(row, 37, false));
schedual.setCompareResultPath(getCellContent(row, 38, false));
// -------------
schedual.setTblStructOutIniPath(getCellContent(row, 39, false));
schedual.setTblStructOutIsCompare(getCellContent(row, 40, false));
schedual.setTblStructOutComparePath(getCellContent(row, 41, false));
schedual.setTblStructOutResultPath(getCellContent(row, 42, false));
// -------------
schedual.setDbChangeType(getCellContent(row, 43, false));
schedual.setDbChangeResultPath(getCellContent(row, 44, false));
// -------------
schedual.setTblScriptOutType(getCellContent(row, 45, false));
schedual.setTblScriptFromPath(getCellContent(row, 46, false));
schedual.setTblScriptResultPath(getCellContent(row, 47, false));
// -------------
schedual.setCreateTblTemplateNm(getCellContent(row, 48, false));
schedual.setCreateTblFromFile(getCellContent(row, 49, false));
schedual.setCreateTblNm(getCellContent(row, 50, false));
schedual.setCreateTblType(getCellContent(row, 51, false));
schedual.setCreateResultPath(getCellContent(row, 52, false));
// -------------
schedual.setOutputTxtAble(getCellContent(row, 53, false));
schedual.setOutputTxtSplit(getCellContent(row, 54, false));
schedual.setOutputTxtCr(getCellContent(row, 55, false));
// ----------------------------------------------------
schedual.setWaitFile(getCellContent(row, 78, false));
schedual.setWaitFileSecond(getCellContent(row, 79, false));
// ----------------------------------------------------
schedual.setDelFolderPath(getCellContent(row, 80, false));
schedual.setDelFileNmReg(getCellContent(row, 81, false));
// ----------------------------------------------------
schedual.setConfigFile(getCellContent(row, 82, false));
schedual.setDbType(getCellContent(row, 83, false));
schedual.setTableSheet(getCellContent(row, 84, false));
schedual.setSplitData(getCellContent(row, 85, false));
schedual.setRecordNum(getCellContent(row, 86, false));
schedual.setExcelType(getCellContent(row, 87, false));
schedual.setInDb(getCellContent(row, 88, false));
schedual.setInLog(getCellContent(row, 89, false));
schedual.setGenrateSql(getCellContent(row, 90, false));
schedual.setInsertAble(getCellContent(row, 91, false));
schedual.setTblNumDisplay(getCellContent(row, 92, false));
schedual.setErrorSkip(getCellContent(row, 93, false));
schedual.setTblClear(getCellContent(row, 94, false));
schedual.setCheckExeType(getCellContent(row, 95, false));
schedual.setLogicCheck(getCellContent(row, 96, false));
schedual.setEncode(getCellContent(row, 97, false));
schedual.setExeType(getCellContent(row, 98, false));
schedual.setBatch(getCellContent(row, 99, false));
///-------------
schedual.setMailFolderPath(getCellContent(row, 100, false));
schedual.setMailTo(getCellContent(row, 101, false));
schedual.setMailTitle(getCellContent(row, 102, false));
schedual.setMailText(getCellContent(row, 103, false));
schedual.setMailZipNm(getCellContent(row, 104, false));
schedual.setMailZipPwd(getCellContent(row, 105, false));
if (CmnStrUtils.isNotEmpty(schedual.getRunTypeStr()) &&CmnStrUtils.isNotEmpty(schedual.getNo()) ) {
treeMap.put(schedual.getNo(), schedual);
}
}
hashMap.put(filePath+CmnLog5j.addlrBracketsM(sheetNameCurrent, false), treeMap);
}
fileInputStream.close();
return hashMap;
}
public static HashMap<String, CsjSheetInfo> getSheetContentsToMap(String filePath,boolean checkStrikeOut) throws Throwable {
HashMap<String, CsjSheetInfo> retMap = new HashMap<String, CsjSheetInfo>();
FileInputStream fileInputStream = new FileInputStream(new File(
filePath));
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileInputStream);
} else if (CmnStrUtils.isEndByIgnor(filePath, CsjConst.EXCEL_DOT_XLS_1997)) {
wb = new HSSFWorkbook(fileInputStream);
}
for (int i = 0; i <wb.getNumberOfSheets(); i++) {
CsjSheetInfo csjSheetInfo =getSheetContents(wb.getSheetAt(i),checkStrikeOut);
csjSheetInfo.setFilePath(filePath);
retMap.put(csjSheetInfo.getSheetNm(), csjSheetInfo);
}
fileInputStream.close();
return retMap;
}
public static CsjSheetInfo getSheetContents(Sheet sheet,
boolean checkStrikeOut) {
CsjSheetInfo retInfo = new CsjSheetInfo();
retInfo.setSheetNm(sheet.getSheetName());
Map<String, CsjCellInfo> cellMap = retInfo.getCsjCellInfoMap();
Map<Integer,CsjColInfo> csjColInfoMap = retInfo.getCsjColInfoMap();
Map<Integer,CsjRowInfo> csjRowInfoMap = retInfo.getCsjRowInfoMap();
Map<String,CsjCellInfo> csjCellPosInfoMap = retInfo.getCsjCellPosInfoMap();
Map<Integer,List<CsjCellInfo>> csjCellPosInfoRowList = retInfo.getCsjCellPosInfoRowList();
Map<Integer,List<CsjCellInfo>> csjCellPosInfoColList = retInfo.getCsjCellPosInfoColList();
try {
String str = CsjConst.EMPTY;
for (Row row : sheet) {
List<CsjCellInfo> rowCells = new ArrayList<CsjCellInfo>();
CsjRowInfo csjRowInfo = new CsjRowInfo();
csjRowInfoMap.put(row.getRowNum(), csjRowInfo);
for (Cell cell : row) {
CsjColInfo csjColInfo = null;
if (csjColInfoMap.containsKey(cell.getColumnIndex())) {
csjColInfo=csjColInfoMap.get(cell.getColumnIndex());
} else {
csjColInfo = new CsjColInfo();
csjColInfoMap.put(cell.getColumnIndex(), csjColInfo);
}
List<CsjCellInfo> colList = null;
if (csjCellPosInfoColList.containsKey(cell.getColumnIndex())) {
colList = csjCellPosInfoColList.get(cell.getColumnIndex());
} else {
colList = new ArrayList<CsjCellInfo>();
csjCellPosInfoColList.put(cell.getColumnIndex(), colList);
}
str = getCellContent( cell, checkStrikeOut);
if (CmnStrUtils.isNotEmpty(str)) {
CsjCellInfo t =CmnPoiUtils.getCellInfo(cell);
t.setSheetNm(sheet.getSheetName());
rowCells.add(t);
cellMap.put(str, t);
csjCellPosInfoMap.put(String.valueOf(row.getRowNum()) + "_" + String.valueOf(cell.getColumnIndex()), t);
csjRowInfo.getRowMap().put(str, t);
csjColInfo.getColMap().put(str, t);
colList.add(t);
}
}
csjCellPosInfoRowList.put(row.getRowNum(), rowCells);
}
} catch (Throwable e) {
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
retInfo.setSheetNm(sheet.getSheetName());
return retInfo;
}
/**
* @param sheet
* @param cellInfo
* @throws Throwable
*/
public static void setCellValue(Sheet sheet, CsjCellInfo cellInfo)
throws Throwable {
if (cellInfo != null && CmnStrUtils.isNotEmpty(cellInfo.getContent()
)) {
setCellValue(sheet, cellInfo.getRowNum(), cellInfo.getCellNum(),
cellInfo.getContent());
}
}
/**
* @param string
* @param string2
* @param i
* @param j
* @param string3
* @throws Throwable
*/
public static void setCellValue(String path, String sheetNm, int row,
int col, String str) throws Throwable {
File file = new File(path);
FileInputStream fileIn = new FileInputStream(file);
Workbook wb = null;
if (CmnStrUtils.isEndByIgnor(path, CsjConst.EXCEL_DOT_XLSX_2007)) {
wb = new XSSFWorkbook(fileIn);
} else {
wb = new HSSFWorkbook(fileIn);
}
setCellValue(wb.getSheet(sheetNm),row,col,str);
FileOutputStream fileOut = new FileOutputStream(path);
wb.write(fileOut);
fileOut.close();
fileIn.close();
}
/**
* @param wb
* @param s_sheetNm
* @return
*/
public static Sheet getOneSheetByNm(Workbook wb, String sheetNm) {
for (int i = wb.getNumberOfSheets()-1; i >=0 ; i--) {
if (!wb.getSheetAt(i).getSheetName().equalsIgnoreCase(sheetNm)) {
wb.removeSheetAt(i);
}
}
return wb.getSheetAt(0);
}
/**
* @param newSt
* @param row
* @param b
* @throws Throwable
*/
public static void copyRow(Sheet newSt, int rowIndex, Row row, boolean isCopyOthers) throws Throwable {
if (newSt == null || row == null) {
return;
}
try {
for (Cell cell : row) {
Cell newCell = setCellValueWithCs(newSt, rowIndex, cell.getColumnIndex(), getCellContent(cell, false), cell.getCellStyle());
newCell.setCellType(cell.getCellType());
newCell.setCellComment(cell.getCellComment());
newCell.setCellFormula(cell.getCellFormula());
}
} catch (Throwable e) {
throw e;
}
}
}
-------C:\aa\common\CmnRandomUtils.java
/**
*
*/
package org.mydbsee.common;
import java.util.HashSet;
import java.util.Random;
/**
* @author Think
*
*/
public class CmnRandomUtils {
public static int getRadomInt(int min,int max) {
return (int) Math.round(Math.random()*(max-min)+min);
}
/**
* 产生一个指定长度的字符串。
*/
public static String createRadomStrs(int length, Boolean isMin,
boolean number) {
char[] result = new char[length];
int m = 0;
for (; m < length;) {
int by = createRadomNum(256, true);
if (number) {
if (isMin == null) {
if ((by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
} else if (isMin) {
if (by >= 97 && by <= 122 || (by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
} else {
if ((by >= 65 && by <= 90) || (by >= 48 && by <= 57)) {
result[m] = (char) by;
m++;
}
}
} else {
if (isMin) {
if ((by >= 97 && by <= 122) || (by >= 65 && by <= 90)) {
result[m] = (char) by;
m++;
}
} else if (isMin) {
if (by >= 97 && by <= 122) {
result[m] = (char) by;
m++;
}
} else {
if ((by >= 65 && by <= 90)) {
result[m] = (char) by;
m++;
}
}
}
}
return String.copyValueOf(result);
}
/**
* 随机指定范围内N个不重复的数
* 最简单最基本的方法
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
*/
public static int[] randomCommon(int min, int max, int n){
if (n > (max - min + 1) || max < min) {
return null;
}
int[] result = new int[n];
int count = 0;
while(count < n) {
int num = (int) (Math.random() * (max - min)) + min;
boolean flag = true;
for (int j = 0; j < n; j++) {
if(num == result[j]){
flag = false;
break;
}
}
if(flag){
result[count] = num;
count++;
}
}
return result;
}
/**
* 随机指定范围内N个不重复的数
* 利用HashSet的特征,只能存放不同的值
* @param min 指定范围最小值
* @param max 指定范围最大值
* @param n 随机数个数
* @param HashSet<Integer> set 随机数结果集
*/
public static void randomSet(int min, int max, int n, HashSet<Integer> set) {
if (n > (max - min + 1) || max < min) {
return;
}
for (int i = 0; i < n; i++) {
// 调用Math.random()方法
int num = (int) (Math.random() * (max - min)) + min;
set.add(num);// 将不同的数存入HashSet中
}
int setSize = set.size();
// 如果存入的数小于指定生成的个数,则调用递归再生成剩余个数的随机数,如此循环,直到达到指定大小
if (setSize < n) {
randomSet(min, max, n - setSize, set);// 递归
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(getRadomInt(1,5));
}
// int[] reult1 = randomCommon(20,50,10);
// for (int i : reult1) {
// System.out.println(i);
// }
// int[] reult2 = randomArray(20,50,31);
// for (int i : reult2) {
// System.out.println(i);
// }
//
// HashSet<Integer> set = new HashSet<Integer>();
// randomSet(20,50,10,set);
// for (int j : set) {
// System.out.println(j);
// }
}
/**
* 随机指定范围内N个不重复的数
* 在初始化的无重复待选数组中随机产生一个数放入结果中,
* 将待选数组被随机到的数,用待选数组(len-1)下标对应的数替换
* 然后从len-2里随机产生下一个随机数,如此类推
* @param max 指定范围最大值
* @param min 指定范围最小值
* @param n 随机数个数
* @return int[] 随机数结果集
*/
public static int[] randomArray(int min,int max,int n){
int len = max-min+1;
if(max < min || n > len){
return null;
}
//初始化给定范围的待选数组
int[] source = new int[len];
for (int i = min; i < min+len; i++){
source[i-min] = i;
}
int[] result = new int[n];
Random rd = new Random();
int index = 0;
for (int i = 0; i < result.length; i++) {
//待选数组0到(len-2)随机一个下标
index = Math.abs(rd.nextInt() % len--);
//将随机到的数放入结果集
result[i] = source[index];
//将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换
source[index] = source[len];
}
return result;
}
/**
* 产生一个的随机整数
*/
public static int createRadomNum(int max, boolean hasZero) {
if (hasZero) {
int s = new Double(max * Math.random()).intValue();
return s;
} else {
int s = new Double(max * Math.random()).intValue();
return s == 0 ? 1 : s;
}
}
/**
* 产生一个的随机Double数
*/
public static Double createRadomDoubleNum(int max, boolean hasZero) {
if (hasZero) {
Double s = new Double(max * Math.random()).doubleValue();
return s;
} else {
Double s = new Double(max * Math.random()).doubleValue();
return s == 0 ? 1.0 : s;
}
}
}
-------C:\aa\common\CmnStrUtils.java
/**
* Copyright (c) 2012, Java CNC/CSJ for tools. All rights reserved.
*/
package org.mydbsee.common;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import jp.co.csj.tools.core.CsjLinkedMap;
import jp.co.csj.tools.utils.common.CsjProcess;
import jp.co.csj.tools.utils.common.constant.CsjConst;
import jp.co.csj.tools.utils.db.core.DbInfo;
import jp.co.csj.tools.utils.db.core.TableDbItem;
import jp.co.csj.tools.utils.poi.core.CsjPosition;
import jp.co.csj.tools.utils.reg.RegConstStr;
import jp.co.csj.tools.utils.schedual.SchedualRec;
import jp.co.csj.tools.utils.schedual.SchedualRecs;
/**
* CsjStrUtils
*
* @author cuishuangjia@163.com
* @version 1.0
* @since 1.6
*/
public class CmnStrUtils {
/**
* @param text
* @return
*/
public static String convertTxtToReg(String text) {
String retStr = text.replace("\\t", "\t");
retStr = retStr.replace("\\0", "\0");
retStr = retStr.replace("\\n", "\n");
retStr = retStr.replace("\\r", "\r");
return retStr;
}
public static List<List<String>> getLstLst(SchedualRecs schedualRecs) {
List<List<String>> retLst = new ArrayList<List<String>>();
Map<String , SchedualRec> schedualRecMap = schedualRecs.getSchedualRecMap();
for (SchedualRec rec : schedualRecMap.values()) {
List<String> sLst = new ArrayList<String>();
if (rec.isChecked() && CmnStrUtils.isNotEmpty(rec.getExcelPath())&&CmnStrUtils.isNotEmpty(rec.getExcelSheetName())) {
sLst.add(rec.getExcelPath());
sLst.add(rec.getExcelSheetName());
}
retLst.add(sLst);
}
return retLst;
}
public static boolean isMatchIgnorReg(String str, String reg) {
if (isNotEmpty(str)) {
return str.toLowerCase().matches(reg.toLowerCase());
}
return false;
}
public static boolean isEndByIgnor(String str, String end) {
if (isNotEmpty(str)) {
return str.toLowerCase().endsWith(end.toLowerCase());
}
return false;
}
public static int getBitesLength(String str) {
int ret = 0;
if (isNotEmpty(str)) {
try {
ret = str.getBytes(IConstFile.ENCODE_SHIFT_JIS).length;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.debug(e.getMessage());
}
}
return ret;
}
public static String getNoNullStr(String str) {
String ret = str;
if (isEmpty(str)) {
ret = CsjConst.EMPTY;
}
return ret;
}
// 判断字符串是否为空(为NULL或者为"")
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof String) {
return obj.toString().length() == 0;
} else if (obj instanceof List) {
return ((List)obj).size()==0;
} else if (obj instanceof Map) {
return ((Map)obj).size()==0;
} else if (obj instanceof Set) {
return ((Set)obj).size()==0;
} else if (obj instanceof Object[]) {
return ((Object[])obj).length==0;
}
return false;
}
public static boolean isNotEmpty(Object obj) {
return !isEmpty(obj);
}
public static boolean isEqual(Object oldObj,Object newObj) {
boolean retVal = false;
if (oldObj==null ||newObj==null) {
return retVal;
}
if (oldObj instanceof String && newObj instanceof String) {
if (String.valueOf(oldObj).equals(newObj)) {
retVal = true;
}
}
return retVal;
}
public static boolean isNotEqual(Object oldObj,Object newObj) {
return !isEqual(oldObj,newObj);
}
public static boolean isEqualIgnorBigSmall(String oldstr, String newstr,boolean trimed) {
boolean retVal = false;
if (oldstr == null || newstr == null) {
return retVal;
}
if (trimed) {
oldstr = fromAtoBByTrim(oldstr, "", "");
newstr = fromAtoBByTrim(newstr, "", "");
}
if (CmnStrUtils.toLowOrUpStr(oldstr).equals(CmnStrUtils.toLowOrUpStr(newstr))) {
retVal = true;
}
return retVal;
}
public static boolean isUptOrIns(String sql) {
if (CmnStrUtils.isEmpty(sql)) {
return false;
}
sql = lrTrimSpace(sql);
if (sql.toLowerCase().startsWith("update")||sql.toLowerCase().startsWith("insert")||sql.toLowerCase().startsWith("delete")) {
return true;
}
return false;
}
/**
* @param paraStr
* @param string
* @param isWithBlank
*/
public static List<String> getListStrSplit(String paraStr, String splitCh,
boolean hasEmpty,boolean islrtrim) {
String[] arrStr = paraStr.split(splitCh,-1);
List<String> retStrList = new ArrayList<String>();
for (String str : arrStr) {
if (islrtrim) {
str = CmnStrUtils.lrTrimSpace(str);
}
if (hasEmpty == false && CmnStrUtils.isEmpty(str)) {
continue;
}
retStrList.add(str);
}
return retStrList;
}
public static List<CsjPosition> getPointList(String str,Set<String> set) {
List<CsjPosition> retList = new ArrayList<CsjPosition>();
str = str.toLowerCase();
for (String s : set) {
int preLenth = 0;
String strTemp = str;
while (strTemp.contains(s)) {
int startPos = strTemp.indexOf(s);
int endPos = startPos+s.length();
retList.add(new CsjPosition(preLenth+startPos, s.length()));
strTemp = strTemp.substring(endPos);
preLenth+=endPos;
}
}
return retList;
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoBByTrim(String str, String strA, String strB) {
String ret = CsjConst.EMPTY;
if (CmnStrUtils.isNotEmpty(str)) {
ret = fromAtoNearB(str, strA, strB);
ret = lrTrimSpace(ret);
}
return ret;
}
public static String hashSet2StrBy(HashSet<String> set, String ch) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(set)) {
Object[] objArr = set.toArray();
for (int i = 0; i < objArr.length; i++) {
if (i + 1 == objArr.length) {
sb.append(String.valueOf(objArr[i]));
} else {
sb.append(String.valueOf(objArr[i]));
sb.append(ch);
}
}
}
return sb.toString();
}
public static String escapeNull(String str) {
if (CmnStrUtils.isEmpty(str)) {
return "";
} else {
return str;
}
}
/**
* @param ret
* @return String
*/
public static String lrTrimSpace(String str) {
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
str = str.trim();
while (str.startsWith(CsjConst.SIGN_SPACE_1)
|| str.startsWith(CsjConst.Z_SIGN_SPACE_1)) {
str = str.substring(1, str.length());
}
while (str.endsWith(CsjConst.SIGN_SPACE_1)
|| str.endsWith(CsjConst.Z_SIGN_SPACE_1)) {
str = str.substring(0, str.length() - 1);
}
return str;
}
public static String lrTrimOnlyOne(String str, String ch,boolean isHead) {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else if (CmnStrUtils.isEmpty(ch)) {
return str;
}
if (isHead) {
if (str.startsWith(ch)) {
str = str.substring(1, str.length());
}
} else {
if (str.endsWith(ch)) {
str = str.substring(0, str.length() - 1);
}
}
return str;
}
public static String lrTrimStartEndBySet(String str, Set<String> chSet,boolean isStart) {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else if (CmnStrUtils.isEmpty(chSet)) {
return str;
}
if (isStart) {
while(true){
if (CmnStrUtils.isEmpty(str)) {
return str;
}
String begin = String.valueOf(str.charAt(0));
if (chSet.contains(begin)) {
str = str.substring(1, str.length());
} else {
break;
}
}
} else {
while(true){
if (CmnStrUtils.isEmpty(str)) {
return str;
}
String begin = String.valueOf(str.charAt(str.length() - 1));
if (chSet.contains(begin)) {
str = str.substring(0, str.length() - 1);
} else {
break;
}
}
}
return str;
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoNearB(String str, String strA, String strB) {
if (null == strA) {
strA = CsjConst.EMPTY;
}
if (null == strB) {
strB = CsjConst.EMPTY;
}
String temp = CsjConst.EMPTY;
int n = 0;
if (CsjConst.EMPTY.equals(strA)) {
if (CsjConst.EMPTY.equals(strB)) {
return str;
}
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
if (CsjConst.EMPTY.equals(strB)) {
if (!CsjConst.EMPTY.equals(strA)) {
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
return str.substring(n);
} else if (n == str.length()) {
return CsjConst.EMPTY;
}
return str;
}
return str;
}
}
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
temp = str.substring(n);
}
if (temp.contains(strB)) {
return temp.substring(0, temp.indexOf(strB));
}
return temp;
} else {
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
}
/**
* @param str
* @param strA
* @param strB
* @return String
*/
public static String fromAtoFarB(String str, String strA, String strB) {
if (null == strA) {
strA = CsjConst.EMPTY;
}
if (null == strB) {
strB = CsjConst.EMPTY;
}
String temp = CsjConst.EMPTY;
int n = 0;
if (CsjConst.EMPTY.equals(strA)) {
if (CsjConst.EMPTY.equals(strB)) {
return str;
}
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
if (CsjConst.EMPTY.equals(strB)) {
if (!CsjConst.EMPTY.equals(strA)) {
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
return str.substring(n);
} else if (n == str.length()) {
return CsjConst.EMPTY;
}
return str;
}
return str;
}
}
if (str.contains(strA)) {
n = str.indexOf(strA) + strA.length();
if (n < str.length()) {
temp = str.substring(n);
}
if (temp.contains(strB)) {
return temp.substring(0, temp.indexOf(strB));
}
return temp;
} else {
if (str.contains(strB)) {
return str.substring(0, str.indexOf(strB));
}
return str;
}
}
/**
*
* @param str
* @param listSignMethod
* @param strB
* @return
*/
public static String fromAtoBByTrimWithStartList(String str,
List<String> listSignMethod, String strB) {
// TODO Auto-generated method stub
for (String string : listSignMethod) {
if (str.contains(string)) {
str = fromAtoBByTrim(str, string, strB);
}
}
return str;
}
/**
*
* @param str
* @param listSignMethod
* @param strB
* @return
*/
public static String fromAtoBByTrimWithEndList(String str,
String strA, List<String> list) {
for (String string : list) {
if (str.contains(string)) {
str = fromAtoBByTrim(str, strA, string);
}
}
return str;
}
public static String funReplace(String rStr, String rFix, String rRep) {
if (isEmpty(rStr)) {
return "";
}
int l = 0;
String gRtnStr = rStr;
do {
l = rStr.indexOf(rFix, l);
if (l == -1)
break;
gRtnStr = rStr.substring(0, l) + rRep
+ rStr.substring(l + rFix.length());
l += rRep.length();
rStr = gRtnStr;
} while (true);
return gRtnStr.substring(0, gRtnStr.length());
}
// 首字母转小写
public static String toLowerCaseFirstOne(String s) {
if (CmnStrUtils.isEmpty(s))
return "";
if (Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder())
.append(Character.toLowerCase(s.charAt(0)))
.append(s.substring(1)).toString();
}
public static String toStr(Object obj) {
if (isNotEmpty(obj)) {
return String.valueOf(obj);
}
return "";
}
// 首字母转大写
public static String toUpperCaseFirstOne(String s) {
if (CmnStrUtils.isEmpty(s)) {
return CsjConst.EMPTY;
}
if (Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder())
.append(Character.toUpperCase(s.charAt(0)))
.append(s.substring(1)).toString();
}
// public static List<HashMap<String, String>> toUpperKeyList(List<HashMap<String, String>> list, HashSet<String> setCol) {
//
// List<HashMap<String, String>> retList = new ArrayList<HashMap<String,String>>();
// for(HashMap<String, String> map : list) {
// HashMap<String, String> inMap = new HashMap<String, String>();
// for (Entry<String, String> entry : map.entrySet()) {
// String key = toLowOrUpStr(entry.getKey());
// String val = entry.getValue();
// if (setCol.contains(key)) {
// val = toLowOrUpStr(val);
// }
// inMap.put(key, val);
// }
// retList.add(inMap);
// }
//
// return retList;
// }
public static long getLongVal(String cellContents) {
long num = 0;
try {
num = (long) Double.parseDouble(cellContents);
} catch (Throwable e) {
//MyLog.logger.info(e.getMessage());
num = 0;
}
return num;
}
public static int getIntVal(String cellContents) {
return (int) getLongVal(cellContents);
}
public static double getDoubleVal(String cellContents)throws Throwable {
double num = 0;
try {
if (cellContents.endsWith("%")) {
cellContents = fromAtoBByTrim(cellContents, "", "%");
}
num = Double.parseDouble(cellContents);
} catch (Throwable e) {
throw e;
// MyLog.logger.info(e.getMessage());
// num = 0;
}
return num;
}
public static String toLowOrUpStr(Object str) {
return convertString(str).toUpperCase();
}
/**
* タイプ転換処理
*
* @param object
* Object
* @return String
*/
public static String convertString(Object object) {
String strResult = null;
if (object == null) {
strResult = "";
} else {
strResult = object.toString();
}
// 返却値を返す
return strResult;
}
public static String[] getArrFromListByRegon(List<String> strList,
boolean isHaveBlank, boolean isInFilter,String filter) {
int blankPos = isHaveBlank ? 1 : 0;
List<String> valList = new ArrayList<String>();
for (String str : strList) {
if (CmnStrUtils.isNotEmpty(filter)) {
if (isInFilter &&str.matches(filter) ) {
} else if (isInFilter==false &&str.matches(filter)==false ) {
} else {
continue;
}
}
valList.add(str);
}
strList = valList;
String[] s = new String[strList.size() + blankPos];
if (isHaveBlank) {
s[0] = "";
for (int i = 0; i < strList.size(); i++) {
s[i + 1] = strList.get(i);
}
} else {
for (int i = 0; i < strList.size(); i++) {
if (CmnStrUtils.isNotEmpty(filter)
&& strList.get(i).contains(filter)) {
continue;
}
s[i] = strList.get(i);
}
}
return s;
}
/**
* @return
*/
public static String[] getArrFromList(List<String> strList,
boolean isHaveBlank, String filter) {
int blankPos = isHaveBlank ? 1 : 0;
List<String> valList = new ArrayList<String>();
for (String str : strList) {
if (CmnStrUtils.isNotEmpty(filter) && str.contains(filter)) {
continue;
}
valList.add(str);
}
strList = valList;
String[] s = new String[strList.size() + blankPos];
if (isHaveBlank) {
s[0] = "";
for (int i = 0; i < strList.size(); i++) {
s[i + 1] = strList.get(i);
}
} else {
for (int i = 0; i < strList.size(); i++) {
if (CmnStrUtils.isNotEmpty(filter)
&& strList.get(i).contains(filter)) {
continue;
}
s[i] = strList.get(i);
}
}
return s;
}
// 字符串右补位
public static String rightFillChar(String str, char c, int length) {
while (length > str.length()) {
str += c;
}
return str;
}
public static String insertChar(String str, String ins,int pos) {
String retStr = "";
if (CmnStrUtils.isEmpty(str)) {
return retStr;
}
if (str.length()<pos) {
return str;
}
return str.substring(0, pos)+ins+str.substring(pos);
}
// 字符串左补位
public static String leftFillChar(String str, char c, int length) {
while (length > str.length()) {
str = c + str;
}
return str;
}
// 字符串左补位
public static String leftFillCharWhithByte(String str, String ch,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
// str = str.substring(0, len);
str = str.substring(str.length() - len, str.length());
}
while (length > str.getBytes("shift-jis").length) {
String oldStr = str;
str = ch + str;
if (length < str.getBytes("shift-jis").length) {
str = " " + oldStr;
}
}
} catch (Throwable e) {
// TODO Auto-generated catch block
// e.printStackTrace();
CmnLog.logger.info(e.getMessage());
e.printStackTrace();
}
return str;
}
// 字符串右补位
public static String rightFillCharWhithByte(String str, String ch,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
// str = str.substring(0, len);
str = str.substring(str.length() - len, str.length());
}
while (length > str.getBytes("shift-jis").length) {
String oldStr = str;
str = str + ch;
if (length < str.getBytes("shift-jis").length) {
str = oldStr + " ";
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
// 字符串右补位
public static String rPadWhithByte(String str, String ch, String chfil,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
str = str.substring(str.length() - len, str.length());
return str;
}
long filLength = length - str.getBytes("shift-jis").length;
str = str + rightFillCharWhithByte(ch, chfil, filLength);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
// 字符串左补位
public static String lPadWhithByte(String str, String ch, String chfil,
long length) {
if (isEmpty(str)) {
str = CsjConst.EMPTY;
}
try {
if (str.length() > length) {
int len = (int) (length);
str = str.substring(str.length() - len, str.length());
return str;
}
long filLength = length - str.getBytes("shift-jis").length;
str = str + leftFillCharWhithByte(ch, chfil, filLength);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
return str;
}
public static int getNumByte(long num) {
int cnt = 0;
if (num == 0) {
return 1;
}
while (num != 0) {
num = num / 10;
cnt++;
}
return cnt;
}
public static String getLastStrBySplit(String line, String splitCh) {
// TODO Auto-generated method stub
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(line)) {
} else if (!line.contains(splitCh)) {
} else {
retStr = line.substring(line.lastIndexOf(splitCh) + 1);
}
return retStr;
}
public static String trimStrByNum(String line, int num, boolean isEnd) {
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(line)) {
} else if (line.length() > num) {
if (isEnd) {
retStr = line.substring(0, line.length() - num);
} else {
retStr = line.substring(num);
}
}
return retStr;
}
public static boolean isNumeric(String str) {
if (isEmpty(str)) {
return false;
}
str = CmnStrUtils.funReplace(str, ".", "");
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
public static String getNumericByStr(String str, boolean isEnd) {
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
int a = 0;
StringBuffer tmSb = new StringBuffer(str);
StringBuffer sb = new StringBuffer();
if (isEnd) {
str = tmSb.reverse().toString();
}
int sz = str.length();
int flg = 0;
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
flg++;
} else {
if (flg != 0) {
break;
}
}
}
if (isEnd) {
sb.reverse();
}
return sb.toString();
}
public static long getAllNumericByStr(String str) {
long retVal = 0;
if (isEmpty(str)) {
return 0;
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
if (sb.length() == 0) {
retVal = 0;
} else {
retVal = Long.parseLong(sb.toString());
}
return retVal;
}
public static String getStringAllNumericByStr(String str) {
long retVal = 0;
if (isEmpty(str)) {
return CsjConst.EMPTY;
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
}
}
if (sb.length() == 0) {
retVal = 0;
} else {
retVal = Long.parseLong(sb.toString());
}
return String.valueOf(retVal);
}
public static String getAllNumABCByStr(String str, boolean isABC123) {
if (isEmpty(str)) {
return "";
}
StringBuffer sb = new StringBuffer();
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (isABC123) {
if (String.valueOf(str.charAt(i))
.matches(RegConstStr.EN_NUM_26)) {
sb.append(str.charAt(i));
}
} else {
if (false == String.valueOf(str.charAt(i)).matches(
RegConstStr.EN_NUM_26)) {
sb.append(str.charAt(i));
}
}
}
return sb.toString();
}
/**
* @param str
* @param signDouble
* @return
*/
public static String addLRSign(String str, String signDouble) {
// TODO Auto-generated method stub
String retStr = CsjConst.EMPTY;
if (CmnStrUtils.isEmpty(str)) {
retStr = CsjConst.EMPTY;
} else {
retStr = signDouble + str + signDouble;
}
return retStr;
}
/**
* @param str
* @param signDouble
* @return
*/
// TODO CSJ
public static HashMap<String, String> getSplitMap(String str,
String bSplit, String sSplit, Set<String> trimChSet,boolean isHead) {
HashMap<String, String> retMap = new HashMap<String, String>();
if (CmnStrUtils.isNotEmpty(str)) {
String[] strBArr = str.split(bSplit);
for (String strB : strBArr) {
if (strB.contains(sSplit)) {
String[] strSArr = strB.split(sSplit);
if (strSArr != null && strSArr.length >= 2) {
String key = "";
String val = "";
if (strSArr.length == 1) {
key = strSArr[0];
} else if (strSArr.length >= 2) {
key = strSArr[0];
val = strSArr[1];
}
val = CmnStrUtils.lrTrimStartEndBySet(val, trimChSet,isHead);
retMap.put(key, val);
}
}
}
}
return retMap;
}
public static InputStream String2ByteArrayInputStream(String str) {
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
return stream;
}
public static InputStream String2InputStreasm(String str) {
ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
return stream;
}
public static String inputStream2String(InputStream is) throws Throwable {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
/**
* @param oldContent
* @param paraLen
* @return
*/
public static String getStrForLength(String str, long paraLen) {
try {
if (CmnStrUtils.isEmpty(str)) {
return CsjConst.EMPTY;
} else {
while (true) {
if (str.getBytes(IConstFile.ENCODE_SHIFT_JIS).length <= paraLen) {
break;
} else {
str = str.substring(0, str.length() - 1);
}
}
}
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.info(e.getMessage());
}
// TODO Auto-generated method stub
return str;
}
public static String getStrForFileNm(String str) {
String retStr = CsjConst.EMPTY;
StringBuffer sb = new StringBuffer();
if (isNotEmpty(str)) {
char[] chArr = str.toCharArray();
for (int i = 0; i < chArr.length; i++) {
String strTmp = String.valueOf(chArr[i]);
if (strTmp.matches(RegConstStr.ERROR_FILE_NM)) {
sb.append(strTmp);
}
}
retStr = sb.toString();
}
return retStr;
}
public static String[] list2StringArr(List<TableDbItem> strList) {
String[] strings = new String[strList.size()];
for (int i = 0; i < strList.size(); i++) {
strings[i] = strList.get(i).getVal();
}
return strings;
}
public static String[][] list2StringArr2(
List<CsjLinkedMap<String, TableDbItem>> list) {
String[][] data = new String[list.size()][];
for (int i = 0; i < data.length; i++) {
data[i] = list2StringArr(list.get(i).toValList(false));
}
return data;
}
/**
* // * @param data
* // * @param list
* //
*/
// public static void list2StringArr2(String[][] data,
// List<CsjLinkedMap<String, String>> list) {
// for (int i = 0; i < data.length; i++) {
// data[i] = list2StringArr(list.get(i).toValList(false));
// }
//
// }
public static List<CsjLinkedMap<String, String>> mapToCsjLinkedMap(
List<HashMap<String, String>> lstMap) {
List<CsjLinkedMap<String, String>> list = new ArrayList<CsjLinkedMap<String, String>>();
for (HashMap lstM : lstMap) {
CsjLinkedMap<String, String> cMap = new CsjLinkedMap<String, String>();
cMap.putAll(lstM);
list.add(cMap);
}
return list;
}
public static List<CsjLinkedMap<String, TableDbItem>> listMap2ListMap(
List<CsjLinkedMap<String, TableDbItem>> list) {
List<CsjLinkedMap<String, TableDbItem>> listMap = new ArrayList<CsjLinkedMap<String, TableDbItem>>();
if (list == null || list.size() == 0) {
return listMap;
}
List<String> keyLst = list.get(0).toKeyList();
int col = keyLst.size();
int row = list.size() + 1;
Object[][] objArr = new Object[row][col];
for (int i = 0; i < col; i++) {
objArr[0][i] = new TableDbItem(keyLst.get(i), keyLst.get(i),
DbInfo.TABLE_COL_TYPE_STR);
}
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < col; j++) {
objArr[i + 1][j] = list.get(i).getValByPos(j);
}
}
for (int i = 1; i < col; i++) {
CsjLinkedMap<String, TableDbItem> map = new CsjLinkedMap<String, TableDbItem>();
for (int j = 0; j < row; j++) {
map.put(((TableDbItem) objArr[j][0]).getVal(),
((TableDbItem) objArr[j][i]));
}
listMap.add(map);
}
return listMap;
}
public static String getStringBySign(Set<String> set,String split) {
String ret = "";
for (String s : set) {
ret+=s;
}
return ret;
}
/**
* @param dbMap
* @param key
*/
public static String getMapValForConvert(HashMap<String, String> map, String key) {
if (isEmpty(map) || map.containsKey(key) == false) {
return key;
} else {
return map.get(key);
}
}
/**
* @param dbMap
* @param key
*/
public static HashSet<String> getSet(String str, String regex, boolean isWithBlank) {
HashSet<String> ret = new HashSet<String>();
if (isEmpty(str)) {
return ret;
}
for (String s : str.split(regex)) {
if (isWithBlank) {
ret.add(s);
} else {
if (isNotEmpty(s)) {
ret.add(s);
}
}
}
return ret;
}
/**
* @param createTblSqlList
*/
public static String getStrByList(List<String> strList) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(strList)) {
for(String str:strList) {
sb.append(str);
}
}
return sb.toString();
}
/**
* @param createTblSqlList
*/
public static String getStrByListWithCr(List<String> strList, boolean isHeadCr) {
StringBuffer sb = new StringBuffer();
if (CmnStrUtils.isNotEmpty(strList)) {
if (isHeadCr) {
sb.append(CsjProcess.s_newLine);
}
for(String str:strList) {
sb.append(str);
}
}
return sb.toString();
}
/**
* @param retStr
* @return
*/
public static String getNumberByTrimDot0(String str) {
if (CmnStrUtils.isNotEmpty(str)) {
if (str.matches(RegConstStr.NUMBER_INTEGER)) {
str = String.valueOf(CmnStrUtils.getIntVal(str));
}
}
return str;
}
/**
* @param equalSet
* @param val
* @return
*/
public static boolean isNumInSet(Set<String> equalSet, String val) throws Throwable{
boolean retVal = false;
try {
BigDecimal bval = new BigDecimal(val);
for (String str : equalSet) {
if (bval.equals(new BigDecimal(str))) {
retVal = true;
}
}
} catch (Throwable e) {
throw e;
}
return retVal;
}
/**
* @param val
* @return
*/
public static boolean isXlsDateStr(String val) {
boolean isXlsDateStr = true;
try {
val = val.replaceAll("-", "/");
String format = CsjConst.EMPTY;
if (val.getBytes(IConstFile.ENCODE_SHIFT_JIS).length > 10) {
format = CsjConst.YYYY_MM_DD_HH_MM_SS_SLASH_24;
} else if (val.getBytes(IConstFile.ENCODE_SHIFT_JIS).length > 19) {
format = CsjConst.YYYY_MM_DD_HH_MM_SS_SLASH_24_SSS;
} else {
format = CsjConst.YYYY_MM_DD_SLASH;
}
isXlsDateStr = CmnDateUtil.checkDate(val, format);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
CmnLog.logger.debug(e.getMessage());
isXlsDateStr = false;
}
return isXlsDateStr;
}
/**
* @param strDate
* @return
*/
public static String getExcelDate(String strDate) {
strDate = CmnStrUtils.fromAtoBByTrim(strDate, "", " 00:00:00.0");
return strDate;
}
public static String subStr(String str, int num) {
String retStr = "";
if (CmnStrUtils.isEmpty(str)) {
return retStr;
}
if (str.length()<num) {
return str;
} else {
return str.substring(0, num);
}
}
public static void main(String[] args) {
System.out.println(fromAtoNearB("a1ggg12", "1", "1"));
}
public static String trimLeftChar(String retVal, String trimCh) {
if (isEmpty(retVal)) {
return CsjConst.EMPTY;
}
while (retVal.startsWith(trimCh)) {
retVal = retVal.substring(1);
}
return retVal;
}
public static String getRealSql(String exeSql, String dbType) {
String presult = exeSql;
try {
String strReg = "(?ms)('(?:''|[^'])*')|--.*?$|/\\*.*?\\*/";
Pattern p = Pattern.compile(strReg);
presult = p.matcher(exeSql).replaceAll("$1");
if (DbInfo.STR_DB_TYPE_MYSQL.equals(dbType)) {
strReg = "(?ms)('(?:''|[^'])*')|#.*?$|/\\*.*?\\*/";
p = Pattern.compile(strReg);
presult = p.matcher(presult).replaceAll("$1");
}
while (presult.startsWith(CsjProcess.s_newLine)) {
presult = presult.substring(presult.indexOf(CsjProcess.s_newLine) + CsjProcess.s_newLine.length());
}
} catch (Exception e) {
CmnLog.logger.error(e.getMessage(), "");
}
return presult;
}
}
-------C:\aa\common\IConstDate.java
package org.mydbsee.common;
public interface IConstDate {
/**
* 時間について
* */
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_24 = "yyyy/MM/dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_24_SSS = "yyyy/MM/dd HH:mm:ss:SSS";
public static final String YYYY_MM_DD_HH_MM_SS_SLASH_12 = "yyyy/MM/dd KK:mm:ss a";
public static final String YYYY_MM_DD_SLASH = "yyyy/MM/dd";
public static final String YYYY_MM_DD = "yyyyMMdd";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_24 = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_24_SSS = "yyyy-MM-dd HH:mm:ss:SSS";
public static final String HH_MM_SS_MINUS_24 = "HHmmss";
public static final String YYYY_MM_DD_HH_MM_SS_MINUS_12 = "yyyy-MM-dd KK:mm:ss a";
public static final String YY_MM_DD_HH_MM_SS_MINUS_24 = "yy/MM/dd";
public static final String YY_MM_DD_HH_MM_SS_SLASH_24 = "yy/MM/dd HH:mm:ss:SSS";
public static final String YYYY_MM_DD_MINUS = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM_SS_ALL_MINUS_24 = "yyyy-MM-dd HH-mm-ss";
public static final String YYYYMMDDHHMMSSMINUS_24 = "yyyyMMddHHmmss";
public static final String YYYYMMDDHH_MMSSMINUS_24 = "yyyyMMdd_HHmmss_SSS";
public static final String YYYYMMDDHH_HHMMSS_24 = "yyyyMMdd_HHmmss";
public static final String YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
}
-------C:\aa\common\IConstFile.java
package org.mydbsee.common;
import jp.co.csj.tools.utils.common.CsjProcess;
public interface IConstFile {
// 文件后缀
public static final String DOT_INI =".ini";
public static final String DOT_INI_BAK = ".ini_bk";
//public static final String DOT_XMLBK =".xmlbk";
public static final int FILE_MAX_LEN = 200-CsjProcess.s_pj_path_length;
// 文件编码形式
public static final String ENCODE_UTF_8 = "utf-8";
public static final String ENCODE_SHIFT_JIS = "shift_jis";
public static final String ENCODE_GBK = "GBK";
public static final String ENCODE_GB2312 = "GB2312";
// ファイルパースまたはファイル
public static final int IS_PATH = 0;
public static final int IS_FILE = 1;
public static final int IS_FILES = 2;
public static final int IS_ERROR = -1;
}
-------C:\aa\common\IConstRegNum.java
/**
*
*/
package org.mydbsee.common;
/**
* @author csj
*
*/
public interface IConstRegNum {
// 非负整数(正整数 +0)
public static final String NUM_01 = "^\\d+$";
// 正整数
public static final String NUM_02 = "^[0-9]*[1-9][0-9]*$";
// 非正整数(负整数 +0)
public static final String NUM_03 = "^((-\\d+)|(0+))$";
// 负整数
public static final String NUM_04 = "^-[0-9]*[1-9][0-9]*$";
// 整数
public static final String NUM_05 = "^-?\\d+$";
// 非负浮点数(正浮点数 +0)
public static final String NUM_06 = "^\\d+(\\.\\d+)?$";
// 正浮点数
public static final String NUM_07 = "^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";
// 非正浮点数(负浮点数 +0)
public static final String NUM_08 = "^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";
// 负浮点数
public static final String NUM_09 = "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$";
// 浮点数
public static final String NUM_10 = "^(-?\\d+)(\\.\\d+)?$";
// 整数或者小数
public static final String NUM_11 = "^[0-9]+\\.{0,1}[0-9]{0,2}$";
// 只能输入数字
public static final String NUM_12 = "^[0-9]*$";
// 只能输入n位的数字
public static final String NUM_13 = "^\\d{n}$";
// 只能输入至少n位的数字
public static final String NUM_14 = "^\\d{n,}$";
// 只能输入m~n位的数字
public static final String NUM_15 = "^\\d{m,n}$";
// 只能输入零和非零开头的数字
public static final String NUM_16 = "^(0|[1-9][0-9]*)$";
// 只能输入有两位小数的正实数
public static final String NUM_17 = "^[0-9]+(.[0-9]{2})?$";
// 只能输入有1~3位小数的正实数
public static final String NUM_18 = "^[0-9]+(.[0-9]{1,3})?$";
// 只能输入非零的正整数
public static final String NUM_19 = "^\\+?[1-9][0-9]*$";
public static void main(String[] args) {
System.out.println("aaaa123,(3.3,1)9dddd".replaceAll("[0-9]|\\.|\\(|\\)|,", ""));
}
}
-------C:\aa\common\IConstRegStr.java
/**
*
*/
package org.mydbsee.common;
/**
* @author csj
*
*/
public interface IConstRegStr {
public static final String EXCEL_REG_DOT = ".+xls|.+xlsx";
public static final String DATE="((^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(10|12|0?[13578])([-\\/\\._])(3[01]|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(11|0?[469])([-\\/\\._])(30|[12][0-9]|0?[1-9])$)|(^((1[8-9]\\d{2})|([2-9]\\d{3}))([-\\/\\._])(0?2)([-\\/\\._])(2[0-8]|1[0-9]|0?[1-9])$)|(^([2468][048]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([3579][26]00)([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][0][48])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][2468][048])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([1][89][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$)|(^([2-9][0-9][13579][26])([-\\/\\._])(0?2)([-\\/\\._])(29)$))";
// 由26个英文字母组成的字符串
public static final String EN_26 = "^[A-Za-z]+$";
// 由26个英文字母的大写组成的字符串
public static final String EN_26_UPP = "^[A-Z]+$";
// 由26个英文字母的小写组成的字符串
public static final String EN_26_LOW = "^[a-z]+$";
// 由数字和26个英文字母组成的字符串
public static final String EN_NUM_26 = "^[A-Za-z0-9]+$";
// 由数字、26个英文字母或者下划线组成的字符串
public static final String EN_NUM_26_UNDER = "^\\w+$";
// email地址
public static final String EMAIL = "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$";//"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
//
// url
public static final String URL = "^[a-zA-z]+:// (\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";
// 验证InternetURL:"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"
public static final String INTERNET_URL = "^[a-zA-z]+:// (\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";
// 只能输入长度为3的字符
public static final String STR_3 = "^.{3}$";
// 验证用户密码(正确格式为:以字母开头,长度在6~18之间,只能包含字符、数字和下划线)
public static final String PASSWORD = "^[a-zA-Z]\\w{5,17}$";
// 删除空行(空格和制表符(tab))
public static final String BLANK_LINE = "^[ \\t]*\\n";
// 非法文件名
public static final String ERROR_FILE_NM = "^[^\\/:*?\"\"<>|]+$";
// 匹配html标签的正则表达式
public static final String HTML = "<(.*)>(.*)<\\/(.*)>|<(.*)\\/>";
// 匹配中文字符的正则表达式:
public static final String STR_CH = "[\u4e00-\u9fa5]";
// 匹配双字节字符(包括汉字在内)
public static final String STR_2 = "[^\\x00-\\xff]";
// 验证由两位数字、一个连字符再加 5 位数字组成的 ID号。
public static final String STR_001 = "/\\d{2}-\\d{5}/";
// 验证一年的12个月(正确格式为:"01"~"09"和"1"~"12")
public static final String MONTH_12 = "^(0?[1-9]|1[0-2])$";
// 验证一个月的31天:"^((0?[1-9])|((1|2)[0-9])|30|31)$"正确格式为;"01"~"09"和"1"~"31"。
public static final String DATE_31 = "^(0?[1-9]|1[0-2])$";
// 验证身份证号(15位或18位数字)
public static final String ID_CARD = "^\\d{15}|\\d{18}$";
// 验证电话号码 正确格式为:"XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。
public static final String TEL_NUMBER = "^(\\(\\d{3,4}-)|\\d{3.4}-)?\\d{7,8}$";
// 只能是jpg和bmp格式
public static final String FILE_END_JPG_BMP= "^(.*)(\\.jpg|\\.bmp)$";
// 只能是xls格式
public static final String FILE_END_XLS= "^(.*)(\\.xls)$";
// 文件夹路径
public static final String FILE_PATH = "\\[^\\]*$";
// SQL表达式
public static final String SQL_CMT_PATH = "--.*|/\\*\\\\*.+?\\\\*\\*/";//"--.*|/\\*.+?\\*/";//"--.*|/\\*.*\\*/"
public static final String SIGN_L_LINE_START = "\\*";
public static final String SIGN_R_LINE_START = "\\*/";
// IP
public static final String IP = "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
// MAC
public static final String MAC = "([0-9A-Fa-f]{2})(-[0-9A-Fa-f]{2}){5}";
// DB TYPE
public static final String DB_TYPE_REPLACE = "[0-9]|\\.|\\(|\\)|,";
public static final String DB_CONVERT_DB = "DB.*";
public static final String DB_CONVERT_TABLE = "TABLE.*";
public static final String DB_CONVERT_COL = "COL.*";
public static final String DOT_HOSI = ".*";
public static final String NUMBER_INTEGER = "^[0-9]*.[0]*$";
public static final String SIGN_T = "\t";
public static final String SIGN_R = "\r";
public static final String SIGN_N = "\n";
public static void main(String[] args) {
System.out.println("aa/*axxxxxa*/aa-abd----dad".replaceAll(SQL_CMT_PATH, ""));
}
/*
* [正则表达式]文本框输入内容控制 默认分类 2009-02-13 10:10 阅读26 评论0 字号: 大大 中中 小小
*
* 验证是否含有^%&',;=?$\"等字符:"[^%&',;=?$\x22]+"。 只能输入汉字:"^[\u4e00-\u9fa5]{0,}$"
* 验证Email地址:"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"。
* 验证InternetURL:"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"。 验证电话号码:
* "^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$"正确格式为:"XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。
*
*
*
* 匹配中文字符的正则表达式: [\u4e00-\u9fa5] 匹配双字节字符(包括汉字在内):[^\x00-\xff]
* 应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) String.prototype.len=function(){return
* this.replace(/[^\x00-\xff]/g,"aa").length;}
*
* 匹配html标签的正则表达式:<(.*)>(.*)<\/(.*)>|<(.*)\/> 匹配首尾空格的正则表达式:(^\s*)|(\s*$)
* 应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:
* String.prototype.trim = function() { return
* this.replace(/(^\s*)|(\s*$)/g, ""); } 利用正则表达式分解和转换IP地址:
* 下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的Javascript程序: function IP2V(ip) {
* re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式 if(re.test(ip)) { return
* RegExp
* .$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
* } else { throw new Error("Not a valid IP address!") } }
* 不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下: var ip="10.100.20.168"
* ip=ip.split(".")
* alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))
* 匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
* 匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
*
* 利用正则表达式限制网页表单里的文本框输入内容:
* 用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
* onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"
* 用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
* onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))"
* 用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^\d]/g,'')
* "onbeforepaste="clipboardData
* .setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"
* 用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData(
* 'text',clipboardData.getData('text').replace(/[^\d]/g,''))" <input
* onkeyup="value=value.replace(/[^\u4E00-\u9FA5\w]/g,'')" onbeforepaste=
* "clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5\w]/g,''))"
* value="允许下划线,数字字母和汉字"> <script language="javascript"> if
* (document.layers)//触发键盘事件 document.captureEvents(Event.KEYPRESS) function
* xz(thsv,nob){ if(nob=="2"){ window.clipboardData.setData("text","")
* alert("避免非法字符输入,请勿复制字符"); return false; } if (event.keyCode!=8 &&
* event.keyCode!=16 && event.keyCode!=37 && event.keyCode!=38 &&
* event.keyCode!=39 && event.keyCode!=40){ thsvv=thsv.value;//输入的值
* thsvs=thsvv.substring(thsvv.length-1);//输入的最后一个字符
* //thsvss=thsvv.substring(0,thsvv.length-1);//去掉最后一个错误字符 if
* (!thsvs.replace(/[^\u4E00-\u9FA5\w]/g,'') ||
* event.keyCode==189){//正则除去符号和下划线 key thsv.value='请勿输入非法符号 ['+thsvs+']';
* alert('请勿输入非法符号 ['+thsvs+']'); thsv.value=""; return false; } } }
* </script> <input onkeyup="xz(this,1)" onPaste="xz(this,2)"
* value="">允许数字字母和汉字 <script language="javascript"> <!-- function
* MaxLength(field,maxlimit){ var j =
* field.value.replace(/[^\x00-\xff]/g,"**").length; //alert(j); var
* tempString=field.value; var tt=""; if(j > maxlimit){ for(var
* i=0;i<maxlimit;i++){ if(tt.replace(/[^\x00-\xff]/g,"**").length <
* maxlimit) tt = tempString.substr(0,i+1); else break; }
* if(tt.replace(/[^\x00-\xff]/g,"**").length > maxlimit)
* tt=tt.substr(0,tt.length-1); field.value = tt; }else{ ; } } </script>
* 单行文本框控制<br /> <INPUT type="text" id="Text1" name="Text1"
* onpropertychange="MaxLength(this, 5)"><br /> 多行文本框控制:<br /> <TEXTAREA
* rows="14" cols="39" id="Textarea1" name="Textarea1"
* onpropertychange="MaxLength(this, 15)"></TEXTAREA><br />
* 控制表单内容只能输入数字,中文.... <script> function test() {
* if(document.a.b.value.length>50) { alert("不能超过50个字符!");
* document.a.b.focus(); return false; } } </script> <form name=a
* onsubmit="return test()"> <textarea name="b" cols="40" wrap="VIRTUAL"
* rows="6"></textarea> <input type="submit" name="Submit" value="check">
* </form> 只能是汉字 <input
* onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"> 只能是英文字符 <script
* language=javascript> function onlyEng() {
* if(!(event.keyCode>=65&&event.keyCode<=90)) event.returnValue=false; }
* </script> <input onkeydown="onlyEng();"> <input name="coname" type="text"
* size="50" maxlength="35" class="input2"
* onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData
* ('text',clipboardData.getData('text').replace(/[^\d]/g,''))"> 只能是数字
* <script language=javascript> function onlyNum() {
* if(!((event.keyCode>=48&&
* event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
* //考虑小键盘上的数字键 event.returnValue=false; } </script> <input
* onkeydown="onlyNum();"> 只能是英文字符和数字 <input
* onkeyup="value=value.replace(/[\W]/g,'')
* "onbeforepaste="clipboardData.setData
* ('text',clipboardData.getData('text').replace(/[^\d]/g,''))"> 验证为email格式
* <SCRIPT LANGUAGE=Javascript RUNAT=Server> function isEmail(strEmail) { if
* (
* strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*
* \.[A-Za-z0-9]+$/) != -1) return true; else alert("oh"); } </SCRIPT>
* <input type=text onblur=isEmail(this.value)> 屏蔽关键字(sex , fuck) - 已修改
* <script language="JavaScript1.2"> function test() { if((a.b.value.indexOf
* ("sex") == 0)||(a.b.value.indexOf ("fuck") == 0)){ alert("五讲四美三热爱");
* a.b.focus(); return false;} } </script> <form name=a
* onsubmit="return test()"> <input type=text name=b> <input type="submit"
* name="Submit" value="check"> </form>
*
* 限制文本框里只能输入数字 <input onkeyup="if(event.keyCode !=37 && event.keyCode !=
* 39) value=value.replace(/\D/g,
* '');"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/\D/g,''))">
* <PIXTEL_MMI_EBOOK_2005>2 </PIXTEL_MMI_EBOOK_2005>
*
* JAVA正则表达式语法(转) 正则表达式语法
*
* 正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为“元字符”)。模式描述在搜索文本时要匹配的一个或多个字符串。
*
* 正则表达式示例
*
* 表达式 匹配 /^\s*$/ 匹配空行。
*
* /\d{2}-\d{5}/ 验证由两位数字、一个连字符再加 5 位数字组成的 ID 号。
*
* /<\s*(\S+)(\s[^>]*)?>[\s\S]*<\s*\/\1\s*>/ 匹配 HTML 标记。
*
* 下表包含了元字符的完整列表以及它们在正则表达式上下文中的行为:
*
*
* 字符 说明 \
* 将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,“n”匹配字符“n”。“\n”匹配换行符。序列“\\”匹配“\”,“\
* (”匹配“(”。
*
* ^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与“\n”或“\r”之后的位置匹配。
*
* $ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与“\n”或“\r”之前的位置匹配。
*
*
* 零次或多次匹配前面的字符或子表达式。例如,zo* 匹配“z”和“zoo”。* 等效于 {0,}。
*
* + 一次或多次匹配前面的字符或子表达式。例如,“zo+”与“zo”和“zoo”匹配,但与“z”不匹配。+ 等效于 {1,}。
*
* ? 零次或一次匹配前面的字符或子表达式。例如,“do(es)?”匹配“do”或“does”中的“do”。? 等效于 {0,1}。
*
* {n} n 是非负整数。正好匹配 n 次。例如,“o{2}”与“Bob”中的“o”不匹配,但与“food”中的两个“o”匹配。
*
* {n,} n 是非负整数。至少匹配 n 次。例如,“o{2,}”不匹配“Bob”中的“o”,而匹配“foooood”中的所有
* o。“o{1,}”等效于“o+”。“o{0,}”等效于“o*”。
*
* {n,m} M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,“o{1,3}”匹配“fooooood”中的头三个
* o。'o{0,1}' 等效于 'o?'。注意:您不能将空格插入逗号和数字之间。
*
* ?
* 当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是“非贪心的”。“非贪心的”模式匹配搜索到的、尽可能短的字符串
* ,而默认的“贪心的”模式匹配搜索到的、尽可能长的字符串。例如,在字符串“oooo”中,“o+?”只匹配单个“o”,而“o+”匹配所有“o”。
*
* . 匹配除“\n”之外的任何单个字符。若要匹配包括“\n”在内的任意字符,请使用诸如“[\s\S]”之类的模式。
*
* (pattern) 匹配 pattern 并捕获该匹配的子表达式。可以使用 $0…$9 属性从结果“匹配”集合中检索捕获的匹配。若要匹配括号字符
* ( ),请使用“\(”或者“\)”。
*
* (?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用“or”字符 (|)
* 组合模式部件的情况很有用。例如,'industr(?:y|ies) 是比 'industry|industries' 更经济的表达式。
*
* (?=pattern) 执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern
* 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?=95|98|NT|2000)'
* 匹配“Windows 2000”中的“Windows”,但不匹配“Windows
* 3.1”中的“Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
*
* (?!pattern) 执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern
* 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,'Windows (?!95|98|NT|2000)'
* 匹配“Windows 3.1”中的 “Windows”,但不匹配“Windows
* 2000”中的“Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。
*
* x|y 匹配 x 或 y。例如,'z|food' 匹配“z”或“food”。'(z|f)ood' 匹配“zood”或“food”。
*
* [xyz] 字符集。匹配包含的任一字符。例如,“[abc]”匹配“plain”中的“a”。
*
* [^xyz] 反向字符集。匹配未包含的任何字符。例如,“[^abc]”匹配“plain”中的“p”。
*
* [a-z] 字符范围。匹配指定范围内的任何字符。例如,“[a-z]”匹配“a”到“z”范围内的任何小写字母。
*
* [^a-z] 反向范围字符。匹配不在指定的范围内的任何字符。例如,“[^a-z]”匹配任何不在“a”到“z”范围内的任何字符。
*
* \b 匹配一个字边界,即字与空格间的位置。例如,“er\b”匹配“never”中的“er”,但不匹配“verb”中的“er”。
*
* \B 非字边界匹配。“er\B”匹配“verb”中的“er”,但不匹配“never”中的“er”。
*
* \cx 匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定
* c 就是“c”字符本身。
*
* \d 数字字符匹配。等效于 [0-9]。
*
* \D 非数字字符匹配。等效于 [^0-9]。
*
* \f 换页符匹配。等效于 \x0c 和 \cL。
*
* \n 换行符匹配。等效于 \x0a 和 \cJ。
*
* \r 匹配一个回车符。等效于 \x0d 和 \cM。
*
* \s 匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。
*
* \S 匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。
*
* \t 制表符匹配。与 \x09 和 \cI 等效。
*
* \v 垂直制表符匹配。与 \x0b 和 \cK 等效。
*
* \w 匹配任何字类字符,包括下划线。与“[A-Za-z0-9_]”等效。
*
* \W 与任何非单词字符匹配。与“[^A-Za-z0-9_]”等效。
*
* \xn 匹配 n,此处的 n
* 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,“\x41”匹配“A”。“\x041”与“\x04”&“
* 1”等效。允许在正则表达式中使用 ASCII 代码。
*
* \num 匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,“(.)\1”匹配两个连续的相同字符。
*
* \n 标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数
* (0-7),那么 n 是八进制转义码。
*
* \nm 标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n
* 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字
* (0-7)。
*
* \nml 当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml。
匹配中文字符的正则表达式: [u4e00-u9fa5]
评注:匹配中文还真是个头疼的事,有了这个表达式就好办了
匹配双字节字符(包括汉字在内):[^x00-xff]
评注:可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
匹配空白行的正则表达式:ns*r
评注:可以用来删除空白行
匹配HTML标记的正则表达式:< (S*?)[^>]*>.*?|< .*? />
评注:网上流传的版本太糟糕,上面这个也仅仅能匹配部分,对于复杂的嵌套标记依旧无能为力
匹配首尾空白字符的正则表达式:^s*|s*$
评注:可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式
匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
评注:表单验证时很实用
匹配网址URL的正则表达式:[a-zA-z]+://[^s]*
评注:网上流传的版本功能很有限,上面这个基本可以满足需求
匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$
评注:表单验证时很实用
匹配国内电话号码:d{3}-d{8}|d{4}-d{7}
评注:匹配形式如 0511-4405222 或 021-87888822
匹配腾讯QQ号:[1-9][0-9]{4,}
评注:腾讯QQ号从10000开始
匹配中国邮政编码:[1-9]d{5}(?!d)
评注:中国邮政编码为6位数字
匹配身份证:d{15}|d{18}
评注:中国的身份证为15位或18位
匹配ip地址:d+.d+.d+.d+
评注:提取ip地址时有用
匹配特定数字:
^[1-9]d*$ //匹配正整数
^-[1-9]d*$ //匹配负整数
^-?[1-9]d*$ //匹配整数
^[1-9]d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]d*.d*|0.d*[1-9]d*$ //匹配正浮点数
^-([1-9]d*.d*|0.d*[1-9]d*)$ //匹配负浮点数
^-?([1-9]d*.d*|0.d*[1-9]d*|0?.0+|0)$ //匹配浮点数
^[1-9]d*.d*|0.d*[1-9]d*|0?.0+|0$ //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]d*.d*|0.d*[1-9]d*))|0?.0+|0$ //匹配非正浮点数(负浮点数 + 0)
评注:处理大量数据时有用,具体应用时注意修正
匹配特定字符串:
^[A-Za-z]+$ //匹配由26个英文字母组成的字符串
^[A-Z]+$ //匹配由26个英文字母的大写组成的字符串
^[a-z]+$ //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$ //匹配由数字和26个英文字母组成的字符串
^w+$ //匹配由数字、26个英文字母或者下划线组成的字符串
在使用RegularExpressionValidator验证控件时的验证功能及其验证表达式介绍如下:
只能输入数字:“^[0-9]*$”
只能输入n位的数字:“^d{n}$”
只能输入至少n位数字:“^d{n,}$”
只能输入m-n位的数字:“^d{m,n}$”
只能输入零和非零开头的数字:“^(0|[1-9][0-9]*)$”
只能输入有两位小数的正实数:“^[0-9]+(.[0-9]{2})?$”
只能输入有1-3位小数的正实数:“^[0-9]+(.[0-9]{1,3})?$”
只能输入非零的正整数:“^+?[1-9][0-9]*$”
只能输入非零的负整数:“^-[1-9][0-9]*$”
只能输入长度为3的字符:“^.{3}$”
只能输入由26个英文字母组成的字符串:“^[A-Za-z]+$”
只能输入由26个大写英文字母组成的字符串:“^[A-Z]+$”
只能输入由26个小写英文字母组成的字符串:“^[a-z]+$”
只能输入由数字和26个英文字母组成的字符串:“^[A-Za-z0-9]+$”
只能输入由数字、26个英文字母或者下划线组成的字符串:“^w+$”
验证用户密码:“^[a-zA-Z]w{5,17}$”正确格式为:以字母开头,长度在6-18之间,
只能包含字符、数字和下划线。
验证是否含有^%&’,;=?$”等字符:“[^%&’,;=?$x22]+”
只能输入汉字:“^[u4e00-u9fa5],{0,}$”
验证Email地址:“^w+[-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*$”
验证InternetURL:“^http://([w-]+.)+[w-]+(/[w-./?%&=]*)?$”
验证电话号码:“^((d{3,4})|d{3,4}-)?d{7,8}$”
正确格式为:“XXXX-XXXXXXX”,“XXXX-XXXXXXXX”,“XXX-XXXXXXX”,
“XXX-XXXXXXXX”,“XXXXXXX”,“XXXXXXXX”。
验证身份证号(15位或18位数字):“^d{15}|d{}18$”
验证一年的12个月:“^(0?[1-9]|1[0-2])$”正确格式为:“01”-“09”和“1”“12”
验证一个月的31天:“^((0?[1-9])|((1|2)[0-9])|30|31)$”
正确格式为:“01”“09”和“1”“31”。
匹配中文字符的正则表达式: [u4e00-u9fa5]
匹配双字节字符(包括汉字在内):[^x00-xff]
匹配空行的正则表达式:n[s| ]*r
匹配HTML标记的正则表达式:/< (.*)>.*|< (.*) />/
匹配首尾空格的正则表达式:(^s*)|(s*$)
匹配Email地址的正则表达式:w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
匹配网址URL的正则表达式:http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?
(1)应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
String.prototype.len=function(){return this.replace([^x00-xff]/g,”aa”).length;}
(2)应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现
String.prototype.trim = function()
{
return this.replace(/(^s*)|(s*$)/g, “”);
}
(3)应用:利用正则表达式分解和转换IP地址
function IP2V(ip) //IP地址转换成对应数值
{
re=/(d+).(d+).(d+).(d+)/g //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
throw new Error(”Not a valid IP address!”)
}
}
*/
}
-------C:\aa\exe\AutoSql.java
package org.mydbsee.common.exe;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.mydbsee.common.CmnDateUtil;
import org.mydbsee.common.CmnFileUtils;
import org.mydbsee.common.CmnLog5j;
import org.mydbsee.common.CmnStrUtils;
import org.mydbsee.common.IConstDate;
import org.mydbsee.common.IConstFile;
public class AutoSql {
public static Map<String,String> commentMap = new HashMap<String,String>();
public static Map<String,String> optypeMap = new HashMap<String,String>();
public static void run() {
try {
String autoTime = CmnDateUtil.getCurrentDateString(IConstDate.YYYYMMDDHH_MMSSMINUS_24);
CmnLog5j.initLog5j(autoTime + "_log.txt",IConstFile.ENCODE_UTF_8);
readFileProperty(commentMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\comment.txt");
readFileProperty(optypeMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\optype.txt");
List<File> flst = CmnFileUtils.getFilesList("C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\FileRecv\\src_1103\\src\\jp\\co\\zc\\card\\ssm", true);
for (File f : flst) {
if (!f.getName().toLowerCase().endsWith(".xml")) {
continue;
}
String directory= "C:\\"+autoTime+ "\\"+ CmnStrUtils.fromAtoNearB(f.getAbsolutePath(), "C:\\", f.getName());
String pjName = CmnStrUtils.fromAtoNearB(f.getName(), "C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\", "\\");
String fileNm = CmnStrUtils.fromAtoNearB(f.getName(), "", ".xml");
List<String> strLst = CmnFileUtils.getFileContent(f, IConstFile.ENCODE_UTF_8);
List<OperateInfo> operateInfoLst = new ArrayList<OperateInfo>();
for (int i=0; i < strLst.size(); i++) {
for (Entry<String,String> entryOpType : optypeMap.entrySet()) {
if (strLst.get(i).toLowerCase().contains(entryOpType.getKey().toLowerCase())) {
OperateInfo operateInfo = new OperateInfo();
operateInfoLst.add(operateInfo);
operateInfo.operateType = entryOpType.getKey().toLowerCase();
operateInfo.id = CmnStrUtils.fromAtoNearB(CmnStrUtils.fromAtoFarB(strLst.get(i), "id", ""), "\"", "\"");
while(!strLst.get(++i).toLowerCase().contains(entryOpType.getValue().toLowerCase())) {
operateInfo.strList.add(strLst.get(i));
}
for (int j = 0; j < operateInfo.strList.size(); j++) {
String line = operateInfo.strList.get(j);
line = getParaLine(line,operateInfo);
line = getCommentLine(line);
operateInfo.strList.set(j, line);
}
writeFile(directory,pjName,fileNm,operateInfo);
}
}
}
}
} catch (Throwable e) {
CmnLog5j.writeLine(e.getStackTrace().toString());
System.out.println(e.getMessage());
} finally {
try {
CmnLog5j.closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
run();
}
private static void writeFile(String path,String pjName, String fileNm, OperateInfo operateInfo) throws Throwable {
File file = new File(path);
file.mkdirs();
BufferedWriter bwOracle = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_O.txt"), IConstFile.ENCODE_UTF_8));
BufferedWriter bwMysql = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_M.txt"), IConstFile.ENCODE_UTF_8));
writeSql(operateInfo, bwOracle,true);
writeSql(operateInfo, bwMysql,false);
}
private static void writeSql(OperateInfo operateInfo, BufferedWriter bw, boolean isOracle) throws Throwable {
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "trasaction");
}
for(Entry<String,String> entry : operateInfo.defineMap.entrySet()) {
String param = entry.getKey();
String type = entry.getValue();
if (isOracle) {
CmnLog5j.writeLineWithConsole(bw, "oaaa" + param + "obbb" + "/*" + type + "*/");
} else {
CmnLog5j.writeLineWithConsole(bw, "maaa" + param + "mbbb" + "/*" + type + "*/");
}
}
for(String str : operateInfo.strList) {
if (isOracle) {
str = str.replace("$$$", "OOOO");
}else {
str = str.replace("$$$", "MMMM");
}
CmnLog5j.writeLineWithConsole(bw, str);
}
CmnLog5j.writeLineWithConsole(bw, ";");
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "rollback;");
}
CmnLog5j.close(bw);
}
private static String getCommentLine(String line) {
String str = line;
System.out.println(str);
for (Entry<String, String> entry : commentMap.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
List<String> list = new ArrayList<String>();
while (str.indexOf(key) >= 0) {
System.out.println(str);
String str1 = str.substring(0, str.indexOf(key));
list.add(str1 + "/*");
if (CmnStrUtils.isEmpty(val)) {
list.add(str.substring(str.indexOf(key)) + "*/");
str = str.substring(str.indexOf(key)+key.length());
} else {
list.add(str.substring(str.indexOf(key), str.indexOf(val) + 1) + "*/");
str = str.substring(str.indexOf(val) + 1);
}
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
str = sb.toString();
}
return str;
}
private static String getParaLine(String line, OperateInfo operateInfo) {
if (!line.contains("#{")) {
return line;
}
String str = line;
List<String> list = new ArrayList<String>();
while(str.indexOf("#{")>=0) {
String str1 = str.substring(0, str.indexOf("#{"));
list.add(str1);
String paraName = CmnStrUtils.fromAtoNearB(str, "#{", ",");
list.add("$$$"+paraName);
String paraType = "XXXXXX";
if (CmnStrUtils.fromAtoNearB(str, "#{", "}").contains("jdbcType=")) {
paraType = CmnStrUtils.fromAtoNearB(str, "jdbcType=", "}");
}
operateInfo.defineMap.put(paraName, paraType);
System.out.println(str);
list.add(str.substring(str.indexOf("#{"), str.indexOf("}")+1));
str = str.substring(str.indexOf("}")+1);
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
return sb.toString();
}
private static void readFileProperty(Map<String,String> map,String filePath) throws Throwable {
List<String> strLst = CmnFileUtils.getFileContent(filePath, IConstFile.ENCODE_UTF_8);
for (String s: strLst) {
String sArr[] = s.split(",");
if (sArr.length==1) {
map.put(sArr[0], null);
} else if (sArr.length==2) {
map.put(sArr[0], sArr[1]);
}
}
}
}
class OperateInfo {
public Map<String,String> defineMap = new LinkedHashMap<String,String>();
public String operateType;
public String id;
public List<String> strList = new ArrayList<>();
}
//<if,>
//#{,}
//<when,>
//<foreach,>
//</foreach>
//<trim,>
//</trim>
//</if>
//<otherwise,>
//</otherwise>
//</when>
//<choose,>
//</choose>
//<set,>
//</set>
//<where,>
//</where>
//<update,</update>
//<select,</select>
//<insert,</insert>
//<delete,</delete>
-------C:\aa\exe\comment.txt
<if,>
#{,}
<when,>
<foreach,>
</foreach>
<trim,>
</trim>
</if>
<otherwise,>
</otherwise>
</when>
<choose,>
</choose>
<set,>
</set>
<where,>
</where>
-------C:\aa\exe\optype.txt
<update,</update>
<select,</select>
<insert,</insert>
<delete,</delete>
-------C:\aa\common\exe\AutoSql.java
package org.mydbsee.common.exe;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.mydbsee.common.CmnDateUtil;
import org.mydbsee.common.CmnFileUtils;
import org.mydbsee.common.CmnLog5j;
import org.mydbsee.common.CmnStrUtils;
import org.mydbsee.common.IConstDate;
import org.mydbsee.common.IConstFile;
public class AutoSql {
public static Map<String,String> commentMap = new HashMap<String,String>();
public static Map<String,String> optypeMap = new HashMap<String,String>();
public static void run() {
try {
String autoTime = CmnDateUtil.getCurrentDateString(IConstDate.YYYYMMDDHH_MMSSMINUS_24);
CmnLog5j.initLog5j(autoTime + "_log.txt",IConstFile.ENCODE_UTF_8);
readFileProperty(commentMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\comment.txt");
readFileProperty(optypeMap,"C:\\Users\\Think\\git\\work\\src\\org\\mydbsee\\common\\exe\\optype.txt");
List<File> flst = CmnFileUtils.getFilesList("C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\FileRecv\\src_1103\\src\\jp\\co\\zc\\card\\ssm", true);
for (File f : flst) {
if (!f.getName().toLowerCase().endsWith(".xml")) {
continue;
}
String directory= "C:\\"+autoTime+ "\\"+ CmnStrUtils.fromAtoNearB(f.getAbsolutePath(), "C:\\", f.getName());
String pjName = CmnStrUtils.fromAtoNearB(f.getName(), "C:\\Users\\Think\\Documents\\Tencent Files\\2796523176\\", "\\");
String fileNm = CmnStrUtils.fromAtoNearB(f.getName(), "", ".xml");
List<String> strLst = CmnFileUtils.getFileContent(f, IConstFile.ENCODE_UTF_8);
List<OperateInfo> operateInfoLst = new ArrayList<OperateInfo>();
for (int i=0; i < strLst.size(); i++) {
for (Entry<String,String> entryOpType : optypeMap.entrySet()) {
if (strLst.get(i).toLowerCase().contains(entryOpType.getKey().toLowerCase())) {
OperateInfo operateInfo = new OperateInfo();
operateInfoLst.add(operateInfo);
operateInfo.operateType = entryOpType.getKey().toLowerCase();
operateInfo.id = CmnStrUtils.fromAtoNearB(CmnStrUtils.fromAtoFarB(strLst.get(i), "id", ""), "\"", "\"");
while(!strLst.get(++i).toLowerCase().contains(entryOpType.getValue().toLowerCase())) {
operateInfo.strList.add(strLst.get(i));
}
for (int j = 0; j < operateInfo.strList.size(); j++) {
String line = operateInfo.strList.get(j);
line = getParaLine(line,operateInfo);
line = getCommentLine(line);
operateInfo.strList.set(j, line);
}
writeFile(directory,pjName,fileNm,operateInfo);
}
}
}
}
} catch (Throwable e) {
CmnLog5j.writeLine(e.getStackTrace().toString());
System.out.println(e.getMessage());
} finally {
try {
CmnLog5j.closeLog5j();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
run();
}
private static void writeFile(String path,String pjName, String fileNm, OperateInfo operateInfo) throws Throwable {
File file = new File(path);
file.mkdirs();
BufferedWriter bwOracle = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_O.txt"), IConstFile.ENCODE_UTF_8));
BufferedWriter bwMysql = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(path + pjName+"_"+fileNm+ "_"+operateInfo.id + "_M.txt"), IConstFile.ENCODE_UTF_8));
writeSql(operateInfo, bwOracle,true);
writeSql(operateInfo, bwMysql,false);
}
private static void writeSql(OperateInfo operateInfo, BufferedWriter bw, boolean isOracle) throws Throwable {
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "trasaction");
}
for(Entry<String,String> entry : operateInfo.defineMap.entrySet()) {
String param = entry.getKey();
String type = entry.getValue();
if (isOracle) {
CmnLog5j.writeLineWithConsole(bw, "oaaa" + param + "obbb" + "/*" + type + "*/");
} else {
CmnLog5j.writeLineWithConsole(bw, "maaa" + param + "mbbb" + "/*" + type + "*/");
}
}
for(String str : operateInfo.strList) {
if (isOracle) {
str = str.replace("$$$", "OOOO");
}else {
str = str.replace("$$$", "MMMM");
}
CmnLog5j.writeLineWithConsole(bw, str);
}
CmnLog5j.writeLineWithConsole(bw, ";");
if (!operateInfo.operateType.toLowerCase().contains("select")) {
CmnLog5j.writeLineWithConsole(bw, "rollback;");
}
CmnLog5j.close(bw);
}
private static String getCommentLine(String line) {
String str = line;
System.out.println(str);
for (Entry<String, String> entry : commentMap.entrySet()) {
String key = entry.getKey();
String val = entry.getValue();
List<String> list = new ArrayList<String>();
while (str.indexOf(key) >= 0) {
System.out.println(str);
String str1 = str.substring(0, str.indexOf(key));
list.add(str1 + "/*");
if (CmnStrUtils.isEmpty(val)) {
list.add(str.substring(str.indexOf(key)) + "*/");
str = str.substring(str.indexOf(key)+key.length());
} else {
list.add(str.substring(str.indexOf(key), str.indexOf(val) + 1) + "*/");
str = str.substring(str.indexOf(val) + 1);
}
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
str = sb.toString();
}
return str;
}
private static String getParaLine(String line, OperateInfo operateInfo) {
if (!line.contains("#{")) {
return line;
}
String str = line;
List<String> list = new ArrayList<String>();
while(str.indexOf("#{")>=0) {
String str1 = str.substring(0, str.indexOf("#{"));
list.add(str1);
String paraName = CmnStrUtils.fromAtoNearB(str, "#{", ",");
list.add("$$$"+paraName);
String paraType = "XXXXXX";
if (CmnStrUtils.fromAtoNearB(str, "#{", "}").contains("jdbcType=")) {
paraType = CmnStrUtils.fromAtoNearB(str, "jdbcType=", "}");
}
operateInfo.defineMap.put(paraName, paraType);
System.out.println(str);
list.add(str.substring(str.indexOf("#{"), str.indexOf("}")+1));
str = str.substring(str.indexOf("}")+1);
}
list.add(str);
StringBuffer sb = new StringBuffer();
for (String s : list) {
sb.append(s);
}
return sb.toString();
}
private static void readFileProperty(Map<String,String> map,String filePath) throws Throwable {
List<String> strLst = CmnFileUtils.getFileContent(filePath, IConstFile.ENCODE_UTF_8);
for (String s: strLst) {
String sArr[] = s.split(",");
if (sArr.length==1) {
map.put(sArr[0], null);
} else if (sArr.length==2) {
map.put(sArr[0], sArr[1]);
}
}
}
}
class OperateInfo {
public Map<String,String> defineMap = new LinkedHashMap<String,String>();
public String operateType;
public String id;
public List<String> strList = new ArrayList<>();
}
//<if,>
//#{,}
//<when,>
//<foreach,>
//</foreach>
//<trim,>
//</trim>
//</if>
//<otherwise,>
//</otherwise>
//</when>
//<choose,>
//</choose>
//<set,>
//</set>
//<where,>
//</where>
//<update,</update>
//<select,</select>
//<insert,</insert>
//<delete,</delete>
-------C:\aa\common\exe\comment.txt
<if,>
#{,}
<when,>
<foreach,>
</foreach>
<trim,>
</trim>
</if>
<otherwise,>
</otherwise>
</when>
<choose,>
</choose>
<set,>
</set>
<where,>
</where>
-------C:\aa\common\exe\optype.txt
<update,</update>
<select,</select>
<insert,</insert>
<delete,</delete>
相关推荐
选项B中的`#KDJF`以非法字符`#`开头;选项C中的`67KDJ`以数字开头。 ### 4. 字符串与字符的区别 - **知识点**: 字符串与单个字符的区别。 - **描述**: 考查字符串与字符的区别以及它们的表示方法。 - **说明**: ...
在这个特定的案例中,"TUNK IS LAOG, ENIEKD KDJF ,KDDD"这部分描述似乎是一串随机字符或加密信息,没有明确揭示资源包的具体内容。不过,我们可以根据常见的资源设计包结构来探讨相关知识点。 在资源设计包中,...
000!!!!!!!!!!!!!!!
基于springboot的文物管理系统源码数据库文档.zip
论文描述:该论文研究了某一特定领域的问题,并提出了新的解决方案。论文首先对问题进行了详细的分析和理解,并对已有的研究成果进行了综述。然后,论文提出了一种全新的解决方案,包括算法、模型或方法。在整个研究过程中,论文使用了合适的实验设计和数据集,并进行了充分的实验验证。最后,论文对解决方案的性能进行了全面的评估和分析,并提出了进一步的研究方向。 源码内容描述:该源码实现了论文中提出的新的解决方案。源码中包含了算法、模型或方法的具体实现代码,以及相关的数据预处理、实验设计和性能评估代码。源码中还包括了合适的注释和文档,以方便其他研究者理解和使用。源码的实现应该具有可读性、可维护性和高效性,并能够复现论文中的实验结果。此外,源码还应该尽可能具有通用性,以便在其他类似问题上进行进一步的应用和扩展。
基于SpringBoot+Vue的美容店信息管理系统源码数据库文档.zip
IMG_9750.PNG
javaweb项目 - 学生管理系统
前端铺子开发者 前端杂货铺 小程序在线课堂+工具组件小程序uniapp移动端.zip
<项目介绍> - 前台技术框架: Bootstrap(一个HTML5响应式框架) 程序开发环境:myEclipse/Eclipse/Idea都可以 + mysql数据库 后台架构框架: SSM(SpringMVC + Spring + Mybatis) - 不懂运行,下载完可以私聊问,可远程教学 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载学习,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可用于毕设、课设、作业等。 下载后请首先打开README.md文件(如有),仅供学习参考, 切勿用于商业用途。 --------
# 基于PaddleDetection框架的人流量统计系统 ## 项目简介 本项目是一个基于PaddleDetection框架的人流量统计系统,专注于静态和动态场景下的人员计数和行人检测。项目涵盖了从数据准备、模型选择、训练、评估、优化到预测和部署的完整流程,旨在提供高效、准确的人流量统计解决方案。 ## 主要特性和功能 多模型支持支持多种模型选择,如DeepSORT、JDE和FairMOT,适用于多目标追踪场景。 模型优化提供多种优化策略,包括数据增强、可变形卷积、syncbn+ema、attention和GIoU Loss,以提升模型精度。 性能加速支持TensorRT推理加速,显著提升模型性能。 数据增强提供多种数据增强方式,如cutmix、syncbn和ema,进一步优化模型性能。 模型导出支持模型导出,便于模型部署和上线。 ## 安装使用步骤 1. 安装PaddleDetection框架 bash
Cocos2d-x教程视频Cocos2d-x游戏实战项目开发记忆卡片提取方式是百度网盘分享地址
此代码基于PTB数据集,实现了一个具有一定泛化能力的语言模型。可指定初始单词和生成单词数生成文本
# 基于MQTT协议和Docker的IoT远程监控管理系统 ## 项目简介 此项目旨在通过MQTT协议实现IoT设备的远程监控与管理,结合Docker技术实现服务器端的轻量化部署。通过Esp32微控制器连接IoT设备和MQTT服务器,实现数据的采集、传输和展示。 ## 项目的主要特性和功能 1. 自动化配置实现Esp32微控制器的自动化配置,通过WiFi连接MQTT服务器。 2. 图形化界面提供图形化界面,方便用户配置WiFi和MQTT服务器的连接凭证。 3. 远程固件更新支持远程固件更新,确保设备始终运行在最新状态。 4. Docker部署利用Docker技术,实现服务器端轻量化部署,方便管理和维护。 5. 实时数据传输通过MQTT协议实现数据的实时传输和展示,适用于多种IoT设备。 ## 安装使用步骤 1. 下载源码下载并解压项目源码文件。 2. 配置Docker环境根据项目需求,配置Docker环境,并启动相应的Docker容器。
# 基于Qt框架的智能家居管理系统 ## 项目简介 本项目是一个基于Qt框架开发的智能家居管理系统,旨在提供一个集成的平台来监控和管理家庭环境中的各种传感器数据,如温度、湿度、烟雾状态、红外状态等。系统通过图形界面实时展示数据,并提供警报功能以应对异常情况。 ## 项目的主要特性和功能 1. 实时数据监控通过Qt和Qwt库创建的曲线图,实时显示温度和湿度数据。 2. 多传感器支持支持温度、湿度、烟雾、红外等多种传感器的监控。 3. 警报系统当传感器数据超过设定阈值时,系统会触发警报,并通过界面显示警告信息。 4. 用户交互提供滑动条和复选框,允许用户调整警报阈值或关闭警报。 5. 网络通信通过TCP套接字与服务器通信,获取和发送传感器数据及网络拓扑信息。 6. 蓝牙数据读取支持通过蓝牙读取传感器数据并更新界面显示。 ## 安装使用步骤 1. 环境准备 确保已安装Qt开发环境。 安装Qwt库以支持曲线图功能。
建立数据库连接池对象(服务器启动)。 按照事先指定的参数创建初始数量的数据库连接(即:空闲连接数)。 对于一个数据库访问请求,直接从连接池中得到一个连接。如果数据库连接池对象中没有空闲的连接,且连接数没有达到最大(即:最大活跃连接数),创建一个新的数据库连接。 存取数据库。 关闭数据库,释放所有数据库连接(此时的关闭数据库连接,并非真正关闭,而是将其放入空闲队列中。如实际空闲连接数大于初始空闲连接数则释放连接)。 释放数据库连接池对象(服务器停止、维护期间,释放数据库连接池对象,并释放所有连接)。
# 基于物联网技术的远程医疗机器人系统 ## 项目简介 本项目通过结合物联网技术和移动设备,实现了一个远程医疗机器人系统。通过远程控制和监测,医生可以在不同地点和环境中进行操作和观察,从而提高医疗服务效率和便利性。本系统的应用场景包括医院、手术室和病房等场景,旨在解决医生无法实时出现在患者身边的问题。 ## 项目的主要特性和功能 本项目的主要特性和功能包括 1. 远程控制医生可以通过BLYNK应用程序控制医疗机器人,实现在远程环境中的导航和操作。 2. 实时监控医疗机器人配备有摄像头和传感器,医生可以实时观察患者情况和手术室环境。 3. 温度监测医疗机器人内置温度传感器,可以测量患者的体温,无需直接接触患者。 4. 药品管理医疗机器人配备有药品箱,可以方便地进行药品的存储和管理。 ## 安装使用步骤 假设用户已经下载了本项目的源码文件,以下是安装使用步骤
# 基于JavaFX的图片管理系统 ## 项目简介 本项目是一个基于JavaFX的图片管理系统,旨在提供一个用户友好的界面来管理和浏览图片。系统支持图片的预览、重命名、删除、复制、粘贴等操作,并提供了多种排序和展示方式。 ## 项目的主要特性和功能 1. 预览窗口 目录树展示 缩略图预览 单选、多选(Ctrl+左键)、框选功能 图片信息显示(如文件名、大小、最后修改时间等) 2. 右键菜单 复制粘贴图片 单选和多选重命名 删除图片 3. 展示窗口 图片放大缩小 左右切换图片 幻灯片播放功能 4. 排序功能 按文件名排序 按文件大小排序 按最后修改时间排序 5. 其他功能 图片信息封装(ImageBean) 文件树节点管理(FileTreeItem)
# 基于TensorFlow的中文文本分类系统 ## 项目简介 本项目是一个基于TensorFlow的中文文本分类系统,使用卷积神经网络(CNN)和循环神经网络(RNN)进行文本分类。项目涵盖了从数据预处理、模型训练、模型评估到模型预测的全流程,旨在提供一个高效的中文文本分类解决方案。 ## 主要特性和功能 数据预处理包括读取文件数据、构建词汇表、转换分类目录、将文本数据转换为ID序列表示等。 模型构建实现了基于CNN和RNN的文本分类模型,支持LSTM和GRU作为RNN的单元。 模型训练提供了详细的训练配置,包括学习率、批次大小、迭代轮次等参数的设置。 模型评估在验证集上评估模型的性能,输出准确率、损失等信息,并生成混淆矩阵。 模型预测加载训练好的模型,对新的文本消息进行分类预测,并输出预测类别。 ## 安装使用步骤 1. 环境准备 安装Python 23 安装TensorFlow 1.3以上
Dbc Rules