Java常用工具类整理一

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代码   收藏代码
  1. //得到TeacherForm  
  2. TeacherForm teacherForm=(TeacherForm)form;  
  3. //构造Teacher对象  
  4. Teacher teacher=new Teacher();  
  5. //赋值  
  6. teacher.setName(teacherForm.getName());  
  7. teacher.setAge(teacherForm.getAge());  
  8. teacher.setGender(teacherForm.getGender());  
  9. teacher.setMajor(teacherForm.getMajor());  
  10. teacher.setDepartment(teacherForm.getDepartment());  
  11.   
  12. //持久化Teacher对象到数据库  
  13. HibernateDAO.save(teacher);  

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

Java代码   收藏代码
  1. TeacherForm teacherForm=(TeacherForm)form;  
  2. Teacher teacher=new Teacher();  
  3.   
  4. BeanUtils.copyProperties(teacher,teacherForm);  
  5.   
  6. 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代码   收藏代码
  1. 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代码   收藏代码
  1. // 写文件  
  2. 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代码   收藏代码
  1. import org.apache.commons.io.FilenameUtils;  
  2.   
  3. public class FilenameUtilsDemoMain {  
  4.       
  5.     public static void main(String[] args) {  
  6.         // 文件路径  
  7.         String path = "D:/SYS_USER_GROUP.SQL";  
  8.   
  9.         // 临时变量  
  10.         String tempVar = null;  
  11.   
  12.         // 得到文件名称(不包括文件后缀名)  
  13.         tempVar = FilenameUtils.getBaseName(path);  
  14.         System.out.println("当前文件名称(不包括文件后缀名):" + tempVar);  
  15.   
  16.         // 得到文件名称(包括文件后缀名)  
  17.         tempVar = FilenameUtils.getName(path);  
  18.         System.out.println("当前文件名称(包括文件后缀名):" + tempVar);  
  19.   
  20.         // 得到文件根目录  
  21.         tempVar = FilenameUtils.getPrefix(path);  
  22.         System.out.println("当前文件根的目录:" + tempVar);  
  23.   
  24.         // 得到当前文件的上一级目录  
  25.         tempVar = FilenameUtils.getFullPathNoEndSeparator(path);  
  26.         System.out.println("当前文件的上一级目录:" + tempVar);  
  27.   
  28.         tempVar = FilenameUtils.getExtension(path);  
  29.         System.out.println("文件扩展名为: "+tempVar);  
  30.     }  
  31. }  
 结果:

当前文件名称(不包括文件后缀名):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代码   收藏代码
  1. if(Arrays.binarySearch(new String[]{"zip"}, ext) >= 0)  

 

6、IOUtils.toInputStream(String)
IOUtils.toString(InputStream)
List IOUtils.readLines(InputStream)

 

Java代码   收藏代码
  1. in.put("md5checksum.txt", IOUtils.toInputStream(detail.toString(), "UTF-8"));  

 

Java代码   收藏代码
  1. IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("META-INF/ws/wsdl.template"));  

 源码:

Java代码   收藏代码
  1. /** 
  2.      * Convert the specified string to an input stream, encoded as bytes 
  3.      * using the default character encoding of the platform. 
  4.      * 
  5.      * @param input the string to convert 
  6.      * @return an input stream 
  7.      * @since Commons IO 1.1 
  8.      */  
  9.     public static InputStream toInputStream(String input) {  
  10.         byte[] bytes = input.getBytes();  
  11.         return new ByteArrayInputStream(bytes);  
  12.     }  
  13.   
  14. public static InputStream toInputStream(String input, String encoding) throws IOException {  
  15.         byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();  
  16.         return new ByteArrayInputStream(bytes);  
  17.     }  

 

Java代码   收藏代码
  1. /** 
  2.      * Writes bytes from a <code>byte[]</code> to an <code>OutputStream</code>. 
  3.      *  
  4.      */  
  5.     public static void write(byte[] data, OutputStream output)  
  6.             throws IOException {  
  7.         if (data != null) {  
  8.             output.write(data);  
  9.         }  
  10.     }  

 

Java代码   收藏代码
  1. /** 
  2.      * Get the contents of an <code>InputStream</code> as a <code>byte[]</code>. 
  3.      */  
  4.     public static byte[] toByteArray(InputStream input) throws IOException {  
  5.         ByteArrayOutputStream output = new ByteArrayOutputStream();  
  6.         copy(input, output);  
  7.         return output.toByteArray();  
  8.     }  
  9.   
  10. public static long copyLarge(InputStream input, OutputStream output)  
  11.             throws IOException {  
  12.         byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
  13.         long count = 0;  
  14.         int n = 0;  
  15.         while (-1 != (n = input.read(buffer))) {  
  16.             output.write(buffer, 0, n);  
  17.             count += n;  
  18.         }  
  19.         return count;  
  20.     }  

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

Java代码   收藏代码
  1. String path = descDir + "MsgHeader.xsd";  
  2.           
  3. String msg = null;  
  4. try {  
  5.     msg = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("META-INF/ws/MsgHeader.template"));               
  6.     msg = String.format(msg, namespacePrefix, systemVersion, System.currentTimeMillis(), typeDefinition);             
  7.     FileUtils.writeStringToFile(new File(path), msg);  
  8.   
  9. catch (Exception e) {  
  10.     e.printStackTrace();  
  11.     logger.error("generateMsgHeaderXsdFile error : " + e.getMessage());  
  12.     throw new ConvertsServiceException(e.getMessage());  
  13. }  

 

 

7、String.format

long timestamp = System.currentTimeMillis();
String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timestamp)

 

 //  %1 第一个参数

//   $t  表示是时间

 http://www.cnblogs.com/xytop/archive/2008/08/26/1277125.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之前


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值