---
title: "常用的一些工具类"
author: "uule"
date: "2011-05-19T13:35:54Z"
tags: ["JavaScript", "SQL", "Spring", "Struts", "数据结构"]
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2017-12-26T17:28:28Z"
id: 1050160
url: "https://uule.iteye.com/blog/1050160"
---

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对象，传统的方式是使用类似下面的语句对属性逐 个赋值：

```
//得到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后，代码就大大改观了，如下所示：

```
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 完成这一工作：

```
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&lt;File&gt; 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

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

 

```
// 写文件
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类来专门帮助我们解决这样的问题。

```
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。注意，这保证了当且仅当此键被找到时，返回的值将 &gt;= 0。

     否则返回 (-(插入点) - 1)这句话要注意：要是查询的的值小于数组里面的最小值那么结果就是-1，  
     如果查询的值大于数组里面的最大值。那么结果就是它的索引值

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

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

 

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

 

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

 

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

 源码：

```
/**
     * 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);
    }
```

 

```
/**
     * 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);
        }
    }
```

 

```
/**
     * 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;
    }
```

**加载模版，填充参数，生成文件：**

```
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  表示是时间

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

 

 **9、System.arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);**

```
/**
	 * 连接合并两个数组
	 */
	public static String[] concatenateStringArrays(String[] array1, String[] array2) {
		if (ObjectUtils.isEmpty(array1)) {
			return array2;
		}
		if (ObjectUtils.isEmpty(array2)) {
			return array1;
		}
		String[] newArr = new String[array1.length + array2.length];
		System.arraycopy(array1, 0, newArr, 0, array1.length);
		System.arraycopy(array2, 0, newArr, array1.length, array2.length);
		return newArr;
	}
```

 

```
/**
	 * Append the given String to the given String array, returning a new array
	 * 添加元素到数组
	 */
	public static String[] addStringToArray(String[] array, String str) {
		if (ObjectUtils.isEmpty(array)) {
			return new String[] {str};
		}
		String[] newArr = new String[array.length + 1];
		System.arraycopy(array, 0, newArr, 0, array.length);
		newArr[array.length] = str;
		return newArr;
	}
```

 

**10、Object\[]  Arrays.copyOf(Object\[] original, int newLength)**

```
Parameters: 
original the array to be copied 
newLength the length of the copy to be returned 
Returns: 
	a copy of the original array, truncated or padded with nulls to obtain the specified length 
```

 

 **11、JAVA中把两个数组合为一个的方法：**

链接：[http://blog.csdn.net/jaycee110905/article/details/9179227](http://blog.csdn.net/jaycee110905/article/details/9179227)

[ArrayUtils学习笔记](http://www.blogjava.net/windonly/archive/2008/02/26/182278.html)  
[Class ArrayUtils](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/ArrayUtils.html#addAll%28byte%5B%5D,%20byte%5B%5D%29)

法1：ArrayUtils.addAll(Object\[], Object\[])方法  
apache-commons包中

```
String[] both = (String[]) ArrayUtils.addAll(first, second);
```

 法2：System.arraycopy()

```
static String[] concat(String[] a, String[] b) {  
   String[] c= new String[a.length+b.length];  
   System.arraycopy(a, 0, c, 0, a.length);  
   System.arraycopy(b, 0, c, a.length, b.length);  
   return c;  
}  
```

 法3：Arrays.copyOf()

```
public static <T> T[] concat(T[] first, T[] second) {  
  T[] result = Arrays.copyOf(first, first.length + second.length);  
  System.arraycopy(second, 0, result, first.length, second.length);  
  return result;  
}   
```

 

```
//合并多个
public static <T> T[] concatAll(T[] first, T[]... rest) {  
  int totalLength = first.length;  
  for (T[] array : rest) {  
    totalLength += array.length;  
  }  
  T[] result = Arrays.copyOf(first, totalLength);  
  int offset = first.length;  
  for (T[] array : rest) {  
    System.arraycopy(array, 0, result, offset, array.length);  
    offset += array.length;  
  }  
  return result;  
}  
```

 使用如下：

String\[] both = concat(first, second);  
String\[] more = concat(first, second, third, fourth);

法4：使用Array.newInstance来生成数组

```
private static <T> T[] concat(T[] a, T[] b) {  
    final int alen = a.length;  
    final int blen = b.length;  
    if (alen == 0) {  
        return b;  
    }  
    if (blen == 0) {  
        return a;  
    }  
    final T[] result = (T[]) java.lang.reflect.Array.  
            newInstance(a.getClass().getComponentType(), alen + blen);  
    System.arraycopy(a, 0, result, 0, alen);  
    System.arraycopy(b, 0, result, alen, blen);  
    return result;  
}  
```

 

 ..

 

 

 

 

。。。