您的位置:首页 > 编程语言 > Java开发

Java常用工具类整理一

2014-07-10 15:18 453 查看
1.Java中计算两个时间的差

javaz中对日期时间的处理比较多,代码中列出了3中日期时间计算差值的方法。

比如:现在是2004-03-26 13:31:40
过去是:2004-01-02 11:30:24
我现在要获得两个日期差,差的形式为:XX天XX小时XX分XX秒

java计算时间差及比较时间大小
比如:现在是2004-03-26 13:31:40
过去是:2004-01-02 11:30:24
我现在要获得两个日期差,差的形式为:XX天XX小时XX分XX秒

方法一:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try
{
Date d1 = df.parse("2004-03-26 13:31:40");
Date d2 = df.parse("2004-01-02 11:30:24");
long diff = d1.getTime() - d2.getTime();
long days = diff / (1000 * 60 * 60 * 24);
}
catch (Exception e)
{
}

方法二: SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date now = df.parse("2004-03-26 13:31:40");
java.util.Date date=df.parse("2004-01-02 11:30:24");
long l=now.getTime()-date.getTime();
long day=l/(24*60*60*1000);
long hour=(l/(60*60*1000)-day*24);
long min=((l/(60*1000))-day*24*60-hour*60);
long s=(l/1000-day*24*60*60-hour*60*60-min*60);
System.out.println(""+day+"天"+hour+"小时"+min+"分"+s+"秒");

方法三:
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date begin=dfs.parse("2004-01-02 11:30:24");
java.util.Date end = dfs.parse("2004-03-26 13:31:40");
long between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒

long day1=between/(24*3600);
long hour1=between%(24*3600)/3600;
long minute1=between%3600/60;
long second1=between%60/60;
System.out.println(""+day1+"天"+hour1+"小时"+minute1+"分"+second1+"秒");

====================================================

java 比较时间大小

String s1="2008-01-25 09:12:09";
String s2="2008-01-29 09:12:11";
java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Calendar c1=java.util.Calendar.getInstance();
java.util.Calendar c2=java.util.Calendar.getInstance();
try
{
c1.setTime(df.parse(s1));
c2.setTime(df.parse(s2));
}catch(java.text.ParseException e){
System.err.println("格式不正确");
}
int result=c1.compareTo(c2);
if(result==0)
System.out.println("c1相等c2");
else if(result<0)
System.out.println("c1小于c2");
else
System.out.println("c1大于c2");


2.Float类型保留两位或多位小数

方法1:用Math.round计算,这里返回的数字格式的.

float price=89.89;
int itemNum=3;
float totalPrice=price*itemNum;
float num=(float)(Math.round(totalPrice*100)/100);//如果要求精确4位就*10000然后/10000
方法2:用DecimalFormat 返回的是String格式的.该类对十进制进行全面的封装.像%号,千分位,小数精度.科学计算.

float price=1.2;
DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
String p=decimalFomat.format(price);//format 返回的是字符串
个人觉得在前台显示金额方面的还是用第二种方式.理由很简单是字符串格式的


3.汉字的字节问题

String name = ‘汉字';
System.out.println(name.getBytes('gbk').length); 结果是4
System.out.println(name.getBytes().length); 结果是6
实际上在gbk编码中每个汉字是2个字节。
UTF-8编码是变长的,1—6个字节。其中汉字编码,是3个或4个字节


private HttpSession getSession(){

RequestAttributes ra = RequestContextHolder.getRequestAttributes();

HttpServletRequest request = ((ServletRequestAttributes)ra).getRequest();

return request.getSession();

}

1、BeanUtils.copyProperties 与PropertyUtils.copyProperties:

BeanUtils提供对Java反射和自省API的包装。其主要目的是利用反射机制对JavaBean的属性进行处理。我们知道,一个JavaBean 通常包含了大量的属性,很多情况下,对JavaBean的处理导致大量get/set代码堆积,增加了代码长度和阅读代码的难度。

BeanUtils是这个包里比较常用的一个工具类,这里只介绍它的copyProperties()方法。该方法定义如下:

比方说把b复制到a,用BeanUtils.copyProperties(a,b)

如果你有两个具有很多相同属性的JavaBean,一个很常见的情况就是Struts里的PO对象(持久对象)和对应的ActionForm,例如 Teacher和TeacherForm。我们一般会在Action里从ActionForm构造一个PO对象,传统的方式是使用类似下面的语句对属性逐 个赋值:

Java代码


//得到TeacherForm

TeacherForm teacherForm=(TeacherForm)form;

//构造Teacher对象

Teacher teacher=new Teacher();

//赋值

teacher.setName(teacherForm.getName());

teacher.setAge(teacherForm.getAge());

teacher.setGender(teacherForm.getGender());

teacher.setMajor(teacherForm.getMajor());

teacher.setDepartment(teacherForm.getDepartment());

//持久化Teacher对象到数据库

HibernateDAO.save(teacher);

而使用BeanUtils后,代码就大大改观了,如下所示:

Java代码


TeacherForm teacherForm=(TeacherForm)form;

Teacher teacher=new Teacher();

BeanUtils.copyProperties(teacher,teacherForm);

HibernateDAO.save(teacher);

如果Teacher和TeacherForm间存在名称不相同的属性,则BeanUtils不 对这些属性进行处理,需要程序员手动处理。例如 Teacher包含modifyDate(该属性记录最后修改日期,不需要用户在界面中输入)属性而TeacherForm无此属性,那么在上面代码的 copyProperties()后还要加上一句:

teacher.setModifyDate(new Date());

怎么样,很方便吧!除BeanUtils外还有一个名为PropertyUtils的工具类,它也提供copyProperties()方法,作用与 BeanUtils的同名方法十分相似,主要的区别在于后者提供类型转换功能,即发现两个JavaBean的同名属性为不同类型时,在支持的数据类型范围内进行转换 ,而前者不支持这个功能,但是速度会更快一些。

2、StringEscapeUtils 提供了 SQL、 HTML、XML、JavaScript、Java 特殊字符的转义和还原 的方法

SQL特殊字符转义

  应该说,您即使没有处理 HTML 或 JavaScript 的特殊字符,也不会带来灾难性的后果,但是如果不在动态构造 SQL 语句时对变量中特殊字符进行处理,将可能导致程序漏洞、数据盗取、数据破坏等严重的安全问题。网络中有大量讲解 SQL 注入的文章,感兴趣的读者可以搜索相关的资料深入研究。

  虽然 SQL 注入的后果很严重,但是只要对动态构造的 SQL 语句的变量进行特殊字符转义处理,就可以避免这一问题的发生了。来看一个存在安全漏洞的经典例子:

SELECT COUNT(userId)

FROM t_user

WHERE userName='”+userName+”' AND password ='”+password+”';

  以上 SQL 语句根据返回的结果数判断用户提供的登录信息是否正确,如果 userName 变量不经过特殊字符转义处理就直接合并到 SQL 语句中,黑客就可以通过将 userName 设置为 “1' or '1'='1”绕过用户名/密码的检查直接进入系统了。

  为了防止他人使用特殊 SQL 字符破坏 SQL 的语句结构或植入恶意操作,必须在变量拼接到 SQL 语句之前对其中的特殊字符进行转义处理。Spring 并没有提供相应的工具类,您可以通过 jakarta commons lang 通用类包中(spring/lib/jakarta-commons/commons-lang.jar )的 StringEscapeUtils 完成这一工作:

Java代码


sb.append(" and h.eglCode like '%" + StringEscapeUtils.escapeSql(hotel.getEglCode()) + "%'");

。。。

3.StringUtils.isEmpty(Str)

org.apache.commons.lang.StringUtils

数组:

4.ArrayUtils.contains(array , value) //boolean

//Checks if the value is in the given array.

ArrayUtils.add(array, value) //返回与array相同的数组类型

//Copies the given array and adds the given element at the end of the new array.

ArrayUtils.isEquals

// 只有当两个数组的数据类型,长度,数值顺序都相同的时候,该方法才会返回True

1 两个数组完全相同

ArrayUtils.isEquals(new int[] { 1, 2, 3 }, new int[] { 1, 2, 3 });// true

2 数据类型以及长度相同,但各个Index上的数据不是一一对应

ArrayUtils.isEquals(new int[] { 1, 3, 2 }, new int[] { 1, 2, 3 });// true

3 数组的长度不一致

ArrayUtils.isEquals(new int[] { 1, 2, 3, 3 }, new int[] { 1, 2, 3 });// false

4 不同的数据类型

ArrayUtils.isEquals(new int[] { 1, 2, 3 }, new long[] { 1, 2, 3 });// false

ArrayUtils.isEquals(new Object[] { 1, 2, 3 }, new Object[] { 1, (long) 2, 3 });// false

5 Null处理,如果输入的两个数组都为null时候则返回true

ArrayUtils.isEquals(new int[] { 1, 2, 3 }, null);// false

ArrayUtils.isEquals(null, null);// true

3、org.apache.commons.io.FileUtils

public static void cleanDirectory(File directory)

Clean a directory without deleting it.

//清空目录

public static void deleteDirectory(File directory)

Recursively delete a directory.

//删除目录

public static Collection<File> listFiles(File directory,

String[] extensions,

boolean recursive)

//列出目录下指定类型的文件

Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.

Parameters:

directory - the directory to search in

extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.

recursive - if true all subdirectories are searched as well

public static String readFileToString(File file,

Charset encoding)

//读出文件内容

Reads the contents of a file into a String. The file is always closed.

Parameters:

file - the file to read, must not be null

encoding - the encoding to use, null means platform default

public static void writeStringToFile(File file,

String data,

Charset encoding)

//从内容转成文件

Writes a String to a file creating the file if it does not exist. NOTE: As from v1.3, the parent directories of the file will be created if they do not exist.

Parameters:

file - the file to write

data - the content to write to the file

encoding - the encoding to use, null means platform default

public static void writeByteArrayToFile(File file,

byte[] data)

Writes a byte array to a file creating the file if it does not exist.

Parameters:

file - the file to write to

data - the content to write to the file

//将字节数组转换为文件,可用于文件上传

Java代码


// 写文件

FileUtils.writeByteArrayToFile(new File(newName), file.getBytes());

格式转换:

FileUtils.writeStringToFile(javaFile,

FileUtils.readFileToString(javaFile, System.getProperty("file.encoding")),

"UTF-8");

File file = new File(path);

//删除旧的文件,如果有的话

try {

if(file.isDirectory()){

FileUtils.deleteDirectory(file);

}

} catch (IOException e) {

e.printStackTrace();

throw new RuntimeException("无法清理旧的文件:("+ path +") "+e.getMessage());

}

4、org.apache.commons.io.FilenameUtils (对文件路径的操作)

有时候我们要在项目中获取文件名称,文件路径,文件后缀名等文件路径信息,commons-io包中的FilenameUtils类给我们把获取这些信息的方法都封装好了,我们就直接调用就好了。

在使用JDK的File类构建目录、文件对象时,通常会碰到以下的问题:

①分隔符的问题:Unix系统和Windos系统的路径分隔符、换行符不同

②路径规范的问题:有些API对于返回的目录路径不带"/",有些则有

③文件名规范的问题:有些文件名中间带有空格,导致程序解析错误

上面的问题虽然不算复杂,却也恼人。有时候甚至会在这些问题上耗费大量的时间。于是Apache commons io包提供了一个FilenameUtils类来专门帮助我们解决这样的问题。

Java代码


import org.apache.commons.io.FilenameUtils;

public class FilenameUtilsDemoMain {

public static void main(String[] args) {

// 文件路径

String path = "D:/SYS_USER_GROUP.SQL";

// 临时变量

String tempVar = null;

// 得到文件名称(不包括文件后缀名)

tempVar = FilenameUtils.getBaseName(path);

System.out.println("当前文件名称(不包括文件后缀名):" + tempVar);

// 得到文件名称(包括文件后缀名)

tempVar = FilenameUtils.getName(path);

System.out.println("当前文件名称(包括文件后缀名):" + tempVar);

// 得到文件根目录

tempVar = FilenameUtils.getPrefix(path);

System.out.println("当前文件根的目录:" + tempVar);

// 得到当前文件的上一级目录

tempVar = FilenameUtils.getFullPathNoEndSeparator(path);

System.out.println("当前文件的上一级目录:" + tempVar);

tempVar = FilenameUtils.getExtension(path);

System.out.println("文件扩展名为: "+tempVar);

}

}

结果:

当前文件名称(不包括文件后缀名):SYS_USER_GROUP

当前文件名称(包括文件后缀名):SYS_USER_GROUP.SQL

当前文件根的目录:D:/

当前文件的上一级目录:D:

文件扩展名为: SQL

5、Arrays.binarySearch()

public static int binarySearch(Object[] a,Object key)

使用二分搜索法来搜索指定数组,以获得指定对象。在进行此调用之前, 必须根据元素的自然顺序对数组进行升序排序(通过 sort(Object[]) 方 法 )。如果没有对数组进行排序,则结果是不确定的。(如果数组包 含不可相互比较的元素(例如,字符串和整数),则无法 根据其元素的自 然顺序对数组进行排序,因此结果是不确定的。)如果数组包含多个等于 指定对象的元素,则无法保证找到的是哪一个。

参数:

a - 要搜索的数组

key - 要搜索的值

返回:

如果它包含在数组中,则返回搜索键的索引;否则返回 - 1 。

插入点 被定义为将键插入数组的那一点:即第一个大于此键的元素索引,

如果数组中的所有元素都小于指定的键,则为 a.length。注意,这保证了当且仅当此键被找到时,返回的值将 >= 0。

否则返回 (-(插入点) - 1)这句话要注意:要是查询的的值小于数组里面的最小值那么结果就是-1,

如果查询的值大于数组里面的最大值。那么结果就是它的索引值

抛出:

ClassCastException - 如果搜索的键不能与数组的元素进行比较。

Java代码


if(Arrays.binarySearch(new String[]{"zip"}, ext) >= 0)

6、IOUtils.toInputStream(String)

IOUtils.toString(InputStream)

List IOUtils.readLines(InputStream)

Java代码


in.put("md5checksum.txt", IOUtils.toInputStream(detail.toString(), "UTF-8"));

Java代码


IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("META-INF/ws/wsdl.template"));

源码:

Java代码


/**

* Convert the specified string to an input stream, encoded as bytes

* using the default character encoding of the platform.

*

* @param input the string to convert

* @return an input stream

* @since Commons IO 1.1

*/

public static InputStream toInputStream(String input) {

byte[] bytes = input.getBytes();

return new ByteArrayInputStream(bytes);

}

public static InputStream toInputStream(String input, String encoding) throws IOException {

byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();

return new ByteArrayInputStream(bytes);

}

Java代码


/**

* Writes bytes from a <code>byte[]</code> to an <code>OutputStream</code>.

*

*/

public static void write(byte[] data, OutputStream output)

throws IOException {

if (data != null) {

output.write(data);

}

}

Java代码


/**

* Get the contents of an <code>InputStream</code> as a <code>byte[]</code>.

*/

public static byte[] toByteArray(InputStream input) throws IOException {

ByteArrayOutputStream output = new ByteArrayOutputStream();

copy(input, output);

return output.toByteArray();

}

public static long copyLarge(InputStream input, OutputStream output)

throws IOException {

byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

long count = 0;

int n = 0;

while (-1 != (n = input.read(buffer))) {

output.write(buffer, 0, n);

count += n;

}

return count;

}

加载模版,填充参数,生成文件:

Java代码


String path = descDir + "MsgHeader.xsd";

String msg = null;

try {

msg = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("META-INF/ws/MsgHeader.template"));

msg = String.format(msg, namespacePrefix, systemVersion, System.currentTimeMillis(), typeDefinition);

FileUtils.writeStringToFile(new File(path), msg);

} catch (Exception e) {

e.printStackTrace();

logger.error("generateMsgHeaderXsdFile error : " + e.getMessage());

throw new ConvertsServiceException(e.getMessage());

}

7、String.format

long timestamp = System.currentTimeMillis();

String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timestamp)

// %1 第一个参数

// $t 表示是时间

/article/7025865.html

8.Arrays.toString(Object[] arr)

String[] cmd = new String[]{"wsimport", "-b", jaxwsC, "-s", src, "-p", pkg, "-verbose", uri, "-Xnocompile"};

logger.debug("cmd : " + Arrays.toString(cmd));

Process process = Runtime.getRuntime().exec(cmd);

InputStream input = process.getInputStream();

reader = new BufferedReader(new InputStreamReader(input));

9.strObj.indexOf(str)

strObj.indexOf(str, startIndex])

//starIndex 可选项。该整数值指出在 String 对象内开始查找的索引。如果省略,则从字符串的开始处查找。

StringBuilder.Append

//将信息追加到当前 StringBuilder 的结尾。

StringBuilder.insert(int offset,String str)

//Inserts the string into this character sequence.

//将字符串或对象插入指定索引处。

//插入offset之前
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: