SerializationUtils |
java |
|
package cn.cd.sg.serialize.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtils {
/**
* @Description:
* @方法名: serialize</p>
* <p>@param : @param object
* <p>@param : @return 设定文件</p>
* @return byte[] 返回类型</p>
* @throws
*/
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(object);
oos.flush();
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
}
return baos.toByteArray();
}
/**
* @Description:
* @方法名: deserialize</p>
* <p>@param : @param bytes
* @return Object 返回类型</p>
* @throws
*/
public static Object deserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
try {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return ois.readObject();
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to deserialize object", ex);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Failed to deserialize object type", ex);
}
}
}
|
ResourceUtils |
java |
|
package cn.cd.sg.resource.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import cn.cd.sg.object.utils.ClassUtils;
import cn.cd.sg.string.utils.StringUtils;
import cn.cd.sg.validate.utils.Validate;
public class ResourceUtils {
/** Pseudo URL prefix for loading from the class path: "classpath:" */
public static final String CLASSPATH_URL_PREFIX = "classpath:";
/** URL prefix for loading from the file system: "file:" */
public static final String FILE_URL_PREFIX = "file:";
/** URL protocol for a file in the file system: "file" */
public static final String URL_PROTOCOL_FILE = "file";
/** URL protocol for an entry from a jar file: "jar" */
public static final String URL_PROTOCOL_JAR = "jar";
/** URL protocol for an entry from a zip file: "zip" */
public static final String URL_PROTOCOL_ZIP = "zip";
/** URL protocol for an entry from a JBoss jar file: "vfszip" */
public static final String URL_PROTOCOL_VFSZIP = "vfszip";
/** URL protocol for a JBoss VFS resource: "vfs" */
public static final String URL_PROTOCOL_VFS = "vfs";
/** URL protocol for an entry from a WebSphere jar file: "wsjar" */
public static final String URL_PROTOCOL_WSJAR = "wsjar";
/** URL protocol for an entry from an OC4J jar file: "code-source" */
public static final String URL_PROTOCOL_CODE_SOURCE = "code-source";
/** Separator between JAR URL and file path within the JAR */
public static final String JAR_URL_SEPARATOR = "!/";
/**
* @Description:
* @方法名: isUrl</p>
* <p>@param : @param resourceLocation
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isUrl(String resourceLocation) {
if (resourceLocation == null) {
return false;
}
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
return true;
}
try {
new URL(resourceLocation);
return true;
}
catch (MalformedURLException ex) {
return false;
}
}
/**
* @Description
* @方法名: getURL</p>
* <p>@param : @param resourceLocation
* <p>@param : @return
* @return URL 返回类型</p>
* @throws
*/
public static URL getURL(String resourceLocation) throws FileNotFoundException {
Validate.notNull(resourceLocation, "Resource location must not be null");
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
URL url = ClassUtils.getDefaultClassLoader().getResource(path);
if (url == null) {
String description = "class path resource [" + path + "]";
throw new FileNotFoundException(
description + " cannot be resolved to URL because it does not exist");
}
return url;
}
try {
// try URL
return new URL(resourceLocation);
}
catch (MalformedURLException ex) {
// no URL -> treat as file path
try {
return new File(resourceLocation).toURI().toURL();
}
catch (MalformedURLException ex2) {
throw new FileNotFoundException("Resource location [" + resourceLocation +
"] is neither a URL not a well-formed file path");
}
}
}
/**
* @Description
* @方法名: getFile</p>
* <p>@param : @param resourceLocation
* <p>@param : @return
* @return File 返回类型</p>
* @throws
*/
public static File getFile(String resourceLocation) throws FileNotFoundException {
Validate.notNull(resourceLocation, "Resource location must not be null");
if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) {
String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length());
String description = "class path resource [" + path + "]";
URL url = ClassUtils.getDefaultClassLoader().getResource(path);
if (url == null) {
throw new FileNotFoundException(
description + " cannot be resolved to absolute file path " +
"because it does not reside in the file system");
}
return getFile(url, description);
}
try {
return getFile(new URL(resourceLocation));
}
catch (MalformedURLException ex) {
return new File(resourceLocation);
}
}
/**
* @Description:
* @方法名: getFile</p>
* <p>@param : @param resourceUrl
* <p>@param : @return
* @return File 返回类型</p>
* @throws
*/
public static File getFile(URL resourceUrl) throws FileNotFoundException {
return getFile(resourceUrl, "URL");
}
/**
* @Description:
* @方法名: getFile</p>
* <p>@param : @param resourceUrl
* <p>@param : @param description
* <p>@param : @return
* @return File 返回类型</p>
* @throws
*/
public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
Validate.notNull(resourceUrl, "Resource URL must not be null");
if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
throw new FileNotFoundException(
description + " cannot be resolved to absolute file path " +
"because it does not reside in the file system: " + resourceUrl);
}
try {
return new File(toURI(resourceUrl).getSchemeSpecificPart());
}
catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new File(resourceUrl.getFile());
}
}
/**
* @Description:
* @方法名: getFile</p>
* <p>@param : @param resourceUri
* <p>@param : @return
* @return File 返回类型</p>
* @throws
*/
public static File getFile(URI resourceUri) throws FileNotFoundException {
return getFile(resourceUri, "URI");
}
/**
* @Description:
* @方法名: getFile</p>
* <p>@param : @param resourceUri
* <p>@param : @param description
* <p>@param : @return
* <p>@param : @throws FileNotFoundException
* @return File 返回类型</p>
* @throws
*/
public static File getFile(URI resourceUri, String description) throws FileNotFoundException {
Validate.notNull(resourceUri, "Resource URI must not be null");
if (!URL_PROTOCOL_FILE.equals(resourceUri.getScheme())) {
throw new FileNotFoundException(
description + " cannot be resolved to absolute file path " +
"because it does not reside in the file system: " + resourceUri);
}
return new File(resourceUri.getSchemeSpecificPart());
}
/**
* @Description:
* @方法名: isFileURL</p>
* <p>@param : @param url
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isFileURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_FILE.equals(protocol) || protocol.startsWith(URL_PROTOCOL_VFS));
}
/**
* @Description:
* @方法名: isJarURL</p>
* <p>@param : @param url
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isJarURL(URL url) {
String protocol = url.getProtocol();
return (URL_PROTOCOL_JAR.equals(protocol) ||
URL_PROTOCOL_ZIP.equals(protocol) ||
URL_PROTOCOL_WSJAR.equals(protocol) ||
(URL_PROTOCOL_CODE_SOURCE.equals(protocol) && url.getPath().contains(JAR_URL_SEPARATOR)));
}
/**
* @Description:
* @方法名: extractJarFileURL</p>
* <p>@param : @param jarUrl
* <p>@param : @return
* <p>@param : @throws MalformedURLException
* @return URL 返回类型</p>
* @throws
*/
public static URL extractJarFileURL(URL jarUrl) throws MalformedURLException {
String urlFile = jarUrl.getFile();
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
if (separatorIndex != -1) {
String jarFile = urlFile.substring(0, separatorIndex);
try {
return new URL(jarFile);
}
catch (MalformedURLException ex) {
// Probably no protocol in original jar URL, like "jar:C:/mypath/myjar.jar".
// This usually indicates that the jar file resides in the file system.
if (!jarFile.startsWith("/")) {
jarFile = "/" + jarFile;
}
return new URL(FILE_URL_PREFIX + jarFile);
}
}
else {
return jarUrl;
}
}
/**
* @Description:
* @方法名: toURI</p>
* <p>@param : @param url
* <p>@param : @return
* <p>@param : @throws URISyntaxException
* @return URI 返回类型</p>
* @throws
*/
public static URI toURI(URL url) throws URISyntaxException {
return toURI(url.toString());
}
/**
* @Description:
* @方法名: toURI</p>
* <p>@param : @param location
* <p>@param : @return
* <p>@param : @throws URISyntaxException
* @return URI 返回类型</p>
* @throws
*/
public static URI toURI(String location) throws URISyntaxException {
return new URI(StringUtils.replace(location, " ", "%20"));
}
}
|
TypeUtils |
java |
|
package cn.cd.sg.reflect.utils;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import cn.cd.sg.object.utils.ClassUtils;
import cn.cd.sg.validate.utils.Validate;
public class TypeUtils {
public static boolean isAssignable(Type lhsType, Type rhsType) {
Validate.notNull(lhsType, "Left-hand side type must not be null");
Validate.notNull(rhsType, "Right-hand side type must not be null");
// all types are assignable to themselves and to class Object
if (lhsType.equals(rhsType) || lhsType.equals(Object.class)) {
return true;
}
if (lhsType instanceof Class<?>) {
Class<?> lhsClass = (Class<?>) lhsType;
// just comparing two classes
if (rhsType instanceof Class<?>) {
return ClassUtils.isAssignable(lhsClass, (Class<?>) rhsType);
}
if (rhsType instanceof ParameterizedType) {
Type rhsRaw = ((ParameterizedType) rhsType).getRawType();
// a parameterized type is always assignable to its raw class
// type
if (rhsRaw instanceof Class<?>) {
return ClassUtils.isAssignable(lhsClass, (Class<?>) rhsRaw);
}
} else if (lhsClass.isArray()
&& rhsType instanceof GenericArrayType) {
Type rhsComponent = ((GenericArrayType) rhsType)
.getGenericComponentType();
return isAssignable(lhsClass.getComponentType(), rhsComponent);
}
}
// parameterized types are only assignable to other parameterized types
// and class types
if (lhsType instanceof ParameterizedType) {
if (rhsType instanceof Class<?>) {
Type lhsRaw = ((ParameterizedType) lhsType).getRawType();
if (lhsRaw instanceof Class<?>) {
return ClassUtils.isAssignable((Class<?>) lhsRaw,
(Class<?>) rhsType);
}
} else if (rhsType instanceof ParameterizedType) {
return isAssignable((ParameterizedType) lhsType,
(ParameterizedType) rhsType);
}
}
if (lhsType instanceof GenericArrayType) {
Type lhsComponent = ((GenericArrayType) lhsType)
.getGenericComponentType();
if (rhsType instanceof Class<?>) {
Class<?> rhsClass = (Class<?>) rhsType;
if (rhsClass.isArray()) {
return isAssignable(lhsComponent, rhsClass
.getComponentType());
}
} else if (rhsType instanceof GenericArrayType) {
Type rhsComponent = ((GenericArrayType) rhsType)
.getGenericComponentType();
return isAssignable(lhsComponent, rhsComponent);
}
}
if (lhsType instanceof WildcardType) {
return isAssignable((WildcardType) lhsType, rhsType);
}
return false;
}
/**
* @Description:
* @方法名: isAssignable</p>
* @param : @param lhsType
* @param : @param rhsType
* @return boolean 返回类型</p>
* @throws
*/
private static boolean isAssignable(ParameterizedType lhsType,
ParameterizedType rhsType) {
if (lhsType.equals(rhsType)) {
return true;
}
Type[] lhsTypeArguments = lhsType.getActualTypeArguments();
Type[] rhsTypeArguments = rhsType.getActualTypeArguments();
if (lhsTypeArguments.length != rhsTypeArguments.length) {
return false;
}
for (int size = lhsTypeArguments.length, i = 0; i < size; ++i) {
Type lhsArg = lhsTypeArguments[i];
Type rhsArg = rhsTypeArguments[i];
if (!lhsArg.equals(rhsArg)
&& !(lhsArg instanceof WildcardType && isAssignable(
(WildcardType) lhsArg, rhsArg))) {
return false;
}
}
return true;
}
/**
* @Description:
* @方法名: isAssignable</p>
* @param : @param lhsType
* @param : @param rhsType
* @return boolean 返回类型</p>
* @throws
*/
private static boolean isAssignable(WildcardType lhsType, Type rhsType) {
Type[] lUpperBounds = lhsType.getUpperBounds();
// supply the implicit upper bound if none are specified
if (lUpperBounds.length == 0) {
lUpperBounds = new Type[] { Object.class };
}
Type[] lLowerBounds = lhsType.getLowerBounds();
// supply the implicit lower bound if none are specified
if (lLowerBounds.length == 0) {
lLowerBounds = new Type[] { null };
}
if (rhsType instanceof WildcardType) {
// both the upper and lower bounds of the right-hand side must be
// completely enclosed in the upper and lower bounds of the left-
// hand side.
WildcardType rhsWcType = (WildcardType) rhsType;
Type[] rUpperBounds = rhsWcType.getUpperBounds();
if (rUpperBounds.length == 0) {
rUpperBounds = new Type[] { Object.class };
}
Type[] rLowerBounds = rhsWcType.getLowerBounds();
if (rLowerBounds.length == 0) {
rLowerBounds = new Type[] { null };
}
for (Type lBound : lUpperBounds) {
for (Type rBound : rUpperBounds) {
if (!isAssignableBound(lBound, rBound)) {
return false;
}
}
for (Type rBound : rLowerBounds) {
if (!isAssignableBound(lBound, rBound)) {
return false;
}
}
}
for (Type lBound : lLowerBounds) {
for (Type rBound : rUpperBounds) {
if (!isAssignableBound(rBound, lBound)) {
return false;
}
}
for (Type rBound : rLowerBounds) {
if (!isAssignableBound(rBound, lBound)) {
return false;
}
}
}
} else {
for (Type lBound : lUpperBounds) {
if (!isAssignableBound(lBound, rhsType)) {
return false;
}
}
for (Type lBound : lLowerBounds) {
if (!isAssignableBound(rhsType, lBound)) {
return false;
}
}
}
return true;
}
public static boolean isAssignableBound(Type lhsType, Type rhsType) {
if (rhsType == null) {
return true;
}
if (lhsType == null) {
return false;
}
return isAssignable(lhsType, rhsType);
}
}
|
ReflectionUtils |
java |
|
package cn.cd.sg.reflect.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import cn.cd.sg.validate.utils.Validate;
public class ReflectionUtils {
static Logger logger = Logger.getLogger(ReflectionUtils.class);
/**
* 描述 : ()
* 方法名: findField
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:06
* @param clazz
* @param name
* @return :Field
*/
public static Field findField(Class<?> clazz, String name) {
return findField(clazz, name, null);
}
/**
* 描述 : ()
* 方法名: findField
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:52:37
* @param clazz
* @param name
* @param type
* @return :Field
*/
public static Field findField(Class<?> clazz, String name, Class<?> type) {
Validate.notNull(clazz, "Class must not be null");
Validate.isTrue(name != null || type != null, "Either name or type of the field must be specified");
Class<?> searchType = clazz;
while (!Object.class.equals(searchType) && searchType != null) {
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields) {
if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
return field;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
/**
* 描述 : ()
* 方法名: setField
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:52:24
* @param field
* @param target
* @param value
* @return :void
*/
public static void setField(Field field, Object target, Object value) {
try {
field.set(target, value);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
throw new IllegalStateException("Unexpected reflection exception - " + ex.getClass().getName() + ": "
+ ex.getMessage());
}
}
/**
* 描述 :
* 方法名: getField
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:51:55
* @param field
* @param target
* @return :Object
*/
public static Object getField(Field field, Object target) {
try {
return field.get(target);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
throw new IllegalStateException(
"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
}
}
/**
* 描述 : ()
* 方法名: findMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:52:14
* @param clazz
* @param name
* @return :Method
*/
public static Method findMethod(Class<?> clazz, String name) {
return findMethod(clazz, name, new Class[0]);
}
/**
* 描述 : ()
* 方法名: findMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:17
* @param clazz
* @param name
* @param paramTypes
* @return :Method
*/
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
Validate.notNull(clazz, "Class must not be null");
Validate.notNull(name, "Method name must not be null");
Class<?> searchType = clazz;
while (searchType != null) {
Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
for (Method method : methods) {
if (name.equals(method.getName())
&& (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
/**
* 描述 : ()
* 方法名: invokeMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:26
* @param method
* @param target
* @return :Object
*/
public static Object invokeMethod(Method method, Object target) {
return invokeMethod(method, target, new Object[0]);
}
/**
* 描述 : ()
* 方法名: invokeMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:34
* @param method
* @param target
* @param args
* @return :Object
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
}
catch (Exception ex) {
handleReflectionException(ex);
}
throw new IllegalStateException("Should never get here");
}
/**
* 描述 : ()
* 方法名: invokeJdbcMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:46
* @param method
* @param target
* @throws SQLException
* @return :Object
*/
public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
return invokeJdbcMethod(method, target, new Object[0]);
}
/**
* 描述 : ()
* 方法名: invokeJdbcMethod
* 创建人:孙刚
* 创建时间:2014-2-7 上午10:53:54
* @param method
* @param target
* @param args
* @throws SQLException
* @return :Object
*/
public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
try {
return method.invoke(target, args);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof SQLException) {
throw (SQLException) ex.getTargetException();
}
handleInvocationTargetException(ex);
}
throw new IllegalStateException("Should never get here");
}
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
handleUnexpectedException(ex);
}
public static void handleInvocationTargetException(InvocationTargetException ex) {
rethrowRuntimeException(ex.getTargetException());
}
public static void rethrowRuntimeException(Throwable ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
handleUnexpectedException(ex);
}
public static void rethrowException(Throwable ex) throws Exception {
if (ex instanceof Exception) {
throw (Exception) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
handleUnexpectedException(ex);
}
private static void handleUnexpectedException(Throwable ex) {
throw new IllegalStateException("Unexpected exception thrown", ex);
}
public static boolean declaresException(Method method, Class<?> exceptionType) {
Validate.notNull(method, "Method must not be null");
Class<?>[] declaredExceptions = method.getExceptionTypes();
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isAssignableFrom(exceptionType)) {
return true;
}
}
return false;
}
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}
public static boolean isEqualsMethod(Method method) {
if (method == null || !method.getName().equals("equals")) {
return false;
}
Class<?>[] paramTypes = method.getParameterTypes();
return (paramTypes.length == 1 && paramTypes[0] == Object.class);
}
public static boolean isHashCodeMethod(Method method) {
return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0);
}
public static boolean isToStringMethod(Method method) {
return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
}
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
&& !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException {
doWithMethods(clazz, mc, null);
}
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf)
throws IllegalArgumentException {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (mf != null && !mf.matches(method)) {
continue;
}
try {
mc.doWith(method);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName()
+ "': " + ex);
}
}
if (clazz.getSuperclass() != null) {
doWithMethods(clazz.getSuperclass(), mc, mf);
}
else if (clazz.isInterface()) {
for (Class<?> superIfc : clazz.getInterfaces()) {
doWithMethods(superIfc, mc, mf);
}
}
}
public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() {
public void doWith(Method method) {
methods.add(method);
}
});
return methods.toArray(new Method[methods.size()]);
}
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException {
doWithFields(clazz, fc, null);
}
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff)
throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy.
Class<?> targetClass = clazz;
do {
Field[] fields = targetClass.getDeclaredFields();
for (Field field : fields) {
// Skip static and final fields.
if (ff != null && !ff.matches(field)) {
continue;
}
try {
fc.doWith(field);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException(
"Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
}
}
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
}
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
if (src == null) {
throw new IllegalArgumentException("Source for field copy cannot be null");
}
if (dest == null) {
throw new IllegalArgumentException("Destination for field copy cannot be null");
}
if (!src.getClass().isAssignableFrom(dest.getClass())) {
throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
+ "] must be same or subclass as source class [" + src.getClass().getName() + "]");
}
doWithFields(src.getClass(), new FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
makeAccessible(field);
Object srcValue = field.get(src);
field.set(dest, srcValue);
}
}, COPYABLE_FIELDS);
}
/**
* Action to take on each method.
*/
public interface MethodCallback {
/**
* Perform an operation using the given method.
* @param method the method to operate on
*/
void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
}
/**
* Callback optionally used to method fields to be operated on by a method callback.
*/
public interface MethodFilter {
/**
* Determine whether the given method matches.
* @param method the method to check
*/
boolean matches(Method method);
}
/**
* Callback interface invoked on each field in the hierarchy.
*/
public interface FieldCallback {
/**
* Perform an operation using the given field.
* @param field the field to operate on
*/
void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
}
/**
* Callback optionally used to filter fields to be operated on by a field callback.
*/
public interface FieldFilter {
boolean matches(Field field);
}
public static FieldFilter COPYABLE_FIELDS = new FieldFilter() {
public boolean matches(Field field) {
return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
}
};
public static MethodFilter NON_BRIDGED_METHODS = new MethodFilter() {
public boolean matches(Method method) {
return !method.isBridge();
}
};
public static MethodFilter USER_DECLARED_METHODS = new MethodFilter() {
public boolean matches(Method method) {
return (!method.isBridge() && method.getDeclaringClass() != Object.class);
}
};
}
|
ConstructorUtils |
java |
|
package cn.cd.sg.reflect.utils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
public class ConstructorUtils {
@SuppressWarnings("unchecked")
private static final Class EMPTY_CLASS_PARAMETERS[] = new Class[0];
private static final Object EMPTY_OBJECT_ARRAY[] = new Object[0];
public ConstructorUtils(){}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:52:37
* @param klass
* @param arg
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeConstructor(Class klass, Object arg)throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
Object args[] = {arg};
return invokeConstructor(klass, args);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:52:27
* @param klass
* @param args
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeConstructor(Class klass, Object args[])throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
if(null == args){
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class parameterTypes[] = new Class[arguments];
for(int i = 0; i < arguments; i++){
parameterTypes[i] = args[i].getClass();
}
return invokeConstructor(klass, args, parameterTypes);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:53:15
* @param klass
* @param args
* @param parameterTypes
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeConstructor(Class klass, Object args[], Class parameterTypes[])throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
if(parameterTypes == null){
parameterTypes = EMPTY_CLASS_PARAMETERS;
}
if (args == null) {
args = EMPTY_OBJECT_ARRAY;
}
Constructor ctor = getMatchingAccessibleConstructor(klass, parameterTypes);
if(null == ctor){
throw new NoSuchMethodException("No such accessible constructor on object: " + klass.getName());
}else {
return ctor.newInstance(args);
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeExactConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:55:03
* @param klass
* @param arg
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeExactConstructor(Class klass, Object arg)
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
Object args[] = {arg};
return invokeExactConstructor(klass, args);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeExactConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:55:49
* @param klass
* @param args
* @return
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeExactConstructor(Class klass, Object args[])
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
if(null == args){
args = EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class parameterTypes[] = new Class[arguments];
for(int i = 0; i < arguments; i++){
parameterTypes[i] = args[i].getClass();
}
return invokeExactConstructor(klass, args, parameterTypes);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: invokeExactConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:57:06
* @param klass
* @param args
* @param parameterTypes
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
* @return :Object
*/
@SuppressWarnings("unchecked")
public static Object invokeExactConstructor(Class klass, Object args[], Class parameterTypes[])
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException{
if(args == null){
args = EMPTY_OBJECT_ARRAY;
}
if (parameterTypes == null) {
parameterTypes = EMPTY_CLASS_PARAMETERS;
}
Constructor ctor = getAccessibleConstructor(klass, parameterTypes);
if (ctor == null) {
throw new NoSuchMethodException("No such accessible constructor on object: " + klass.getName());
}else {
return ctor.newInstance(args);
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: getAccessibleConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:58:38
* @param klass
* @param parameterType
* @return
* @return :Constructor
* @throws NoSuchMethodException
* @throws SecurityException
*/
@SuppressWarnings("unchecked")
public static Constructor getAccessibleConstructor(Class klass, Class parameterType) throws SecurityException, NoSuchMethodException{
Class parameterTypes[] = {parameterType};
return getAccessibleConstructor(klass, parameterTypes);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: getAccessibleConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午09:59:16
* @param klass
* @param parameterTypes
* @return
* @return :Constructor
* @throws NoSuchMethodException
* @throws SecurityException
*/
@SuppressWarnings("unchecked")
public static Constructor getAccessibleConstructor(Class klass, Class parameterTypes[]) throws SecurityException, NoSuchMethodException{
return getAccessibleConstructor(klass.getConstructor(parameterTypes));
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: getAccessibleConstructor
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:01:17
* @param ctor
* @return
* @return :Constructor
*/
@SuppressWarnings("unchecked")
public static Constructor getAccessibleConstructor(Constructor ctor){
if(ctor == null){
return null;
}
if(!Modifier.isPublic(ctor.getModifiers())){
return null;
}
Class clazz = ctor.getDeclaringClass();
if(Modifier.isPublic(clazz.getModifiers())){
return ctor;
}else {
return null;
}
}
@SuppressWarnings("unchecked")
private static Constructor getMatchingAccessibleConstructor(Class clazz, Class parameterTypes[]) throws SecurityException, NoSuchMethodException{
Constructor ctor;
ctor = clazz.getConstructor(parameterTypes);
ctor.setAccessible(true);
return ctor;
}
}
|
AnnotationUtils |
java |
|
package cn.cd.sg.reflect.utils;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.cd.sg.array.utils.ArrayUtils;
/**
* 描述:(注解 工具类)
* 项目名称:utils
* 类名称:AnnotationUtils
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:13:21
* 修改人1:xxx
* 修改时间1:xxxx-xx-xx
* 修改备注:
* @version 1.0
*/
@SuppressWarnings("unchecked")
public class AnnotationUtils {
private static final Pattern SETTER_PATTERN = Pattern.compile("set([A-Z][A-Za-z0-9]*)$");
private static final Pattern GETTER_PATTERN = Pattern.compile("(get|is|has)([A-Z][A-Za-z0-9]*)$");
/**
* 描述 : ()
* 方法名: addAllFields
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:14:09
* @param annotationClass
* @param clazz
* @param allFields
* @return :void
*/
public static void addAllFields(Class annotationClass, Class clazz, List allFields){
if (clazz == null) {
return;
}
Field fields[] = clazz.getDeclaredFields();
Field arr$[] = fields;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++){
Field field = arr$[i$];
Annotation ann = field.getAnnotation(annotationClass);
if(ann != null){
allFields.add(field);
}
}
addAllFields(annotationClass, clazz.getSuperclass(), allFields);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: addAllMethods
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:19:00
* @param annotationClass
* @param clazz
* @param allMethods
* @return :void
*/
public static void addAllMethods(Class annotationClass, Class clazz, List allMethods){
if(clazz == null){
return ;
}
Method methods[] = clazz.getDeclaredMethods();
Method arr$[] = methods;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++){
Method method = arr$[i$];
Annotation ann = method.getAnnotation(annotationClass);
if(ann != null){
allMethods.add(method);
}
}
addAllMethods(annotationClass, clazz.getSuperclass(), allMethods);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: addAllInterfaces
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:21:07
* @param clazz
* @param allInterfaces
* @return :void
*/
public static void addAllInterfaces(Class clazz, List allInterfaces){
if(clazz == null){
return;
}else {
Class interfaces[] = clazz.getInterfaces();
allInterfaces.addAll(Arrays.asList(interfaces));
addAllInterfaces(clazz.getSuperclass(), allInterfaces);
return;
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: getAnnotatedMethods
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:22:24
* @param clazz
* @param annotation
* @return
* @return :Collection
*/
public static final Collection getAnnotatedMethods(Class clazz, Class annotation[]){
Collection toReturn = new HashSet();
Method arr$[] = clazz.getMethods();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++){
Method m = arr$[i$];
if (ArrayUtils.isNotEmpty(annotation) && isAnnotatedBy(m, annotation)) {
toReturn.add(m);
continue;
}
if (ArrayUtils.isEmpty(annotation) && ArrayUtils.isNotEmpty(m.getAnnotations())) {
toReturn.add(m);
}
}
return toReturn;
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: isAnnotatedBy
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:27:15
* @param annotatedElement
* @param annotation
* @return
* @return :boolean
*/
public static final boolean isAnnotatedBy(AnnotatedElement annotatedElement, Class annotation[]){
if(ArrayUtils.isEmpty(annotation)) {
return false;
}
Class arr$[] = annotation;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++){
Class c = arr$[i$];
if(annotatedElement.isAnnotationPresent(c)){
return true;
}
}
return false;
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: findAnnotatedMethods
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:31:54
* @param clazz
* @param annotationClass
* @return
* @return :List
*/
public static List findAnnotatedMethods(Class clazz, Class annotationClass){
List methods = new ArrayList();
findRecursively(clazz, annotationClass, methods);
return methods;
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: findRecursively
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:32:26
* @param clazz
* @param annotationClass
* @param methods
* @return :void
*/
public static void findRecursively(Class clazz, Class annotationClass, List methods){
Method arr$[] = clazz.getDeclaredMethods();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++) {
Method m = arr$[i$];
if(m.getAnnotation(annotationClass) != null){
methods.add(0, m);
}
}
if(clazz.getSuperclass() != Object.class){
findRecursively(clazz.getSuperclass(), annotationClass, methods);
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: resolvePropertyName
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:34:07
* @param method
* @return
* @return :String
*/
public static String resolvePropertyName(Method method){
Matcher matcher = SETTER_PATTERN.matcher(method.getName());
if(matcher.matches() && method.getParameterTypes().length == 1){
String raw = matcher.group(1);
return (new StringBuilder()).append(raw.substring(0, 1).toLowerCase()).append(raw.substring(1)).toString();
}
matcher = GETTER_PATTERN.matcher(method.getName());
if(matcher.matches() && method.getParameterTypes().length == 0){
String raw = matcher.group(2);
return (new StringBuilder()).append(raw.substring(0, 1).toLowerCase()).append(raw.substring(1)).toString();
}else {
return null;
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: find
* 创建人:孙刚
* 创建时间:2014-1-22 下午03:35:50
* @param clazz
* @param pckgname
* @return
* @return :String[]
*/
public static String[] find(Class clazz, String pckgname){
List classes = new ArrayList();
String name = new String(pckgname);
if(!name.startsWith("/")){
name = (new StringBuilder()).append("/").append(name).toString();
}
name = name.replace('.', File.separatorChar);
URL url = clazz.getResource(name);
File directory = new File(url.getFile());
if(directory.exists()){
String files[] = directory.list();
String arr$[] = files;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++){
String file = arr$[i$];
if(file.endsWith(".class")){
classes.add((new StringBuilder()).append(pckgname).append(".").append(file.substring(0, file.length() - 6)).toString());
}
}
}
return (String[])classes.toArray(new String[classes.size()]);
}
}
|
PropertyUtils |
java |
|
package cn.cd.sg.properties.utils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;
public class PropertyUtils {
private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前
private static Properties config = null;// 本系统的配置
static {
config = new Properties();
try {
System.out.println(1);
//config = getPropertiesMap("/jdbc.properties");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @author 读取properties配置文件的内容
* @param filepath
* 配置文件相对路径
* @return 返回Properites对象
* */
public static Properties getPropertiesMap(String filepath)
throws IOException {
String fpath = PropertyUtils.class.getClassLoader().getResource(filepath) .getPath();
// String fpath = FileUtil.class.getResource(filepath).getPath();
// 去除路径空格问题
fpath = java.net.URLDecoder.decode(fpath, "UTF-8");
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(fpath));
} catch (IOException e) {
e.printStackTrace();
}
Properties p = new Properties();
p.load(in);
return p;
}
/**
* 读取配置文件
* @param fileName
* @return
*/
public static Properties getProperties(String fileName){
InputStream in = null;
try {
config = register.get(fileName);
if (config == null) {
in = new FileInputStream(fileName);
if (fileName.startsWith("/")) {
in = PropertyUtils.class.getResourceAsStream(fileName);
}else {
in = PropertyUtils.class.getResourceAsStream("/"+fileName);
}
config = new Properties();
config.load(in);
register.put(fileName, config);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return config;
}
public static String getConfigParam(String key){
return config.getProperty(key);
}
}
|
ObjectUtils |
java |
|
package cn.cd.sg.object.utils;
import java.lang.reflect.Array;
import java.util.Arrays;
public class ObjectUtils {
private static final int INITIAL_HASH = 7;
private static final int MULTIPLIER = 31;
private static final String EMPTY_STRING = "";
private static final String NULL_STRING = "null";
private static final String ARRAY_START = "{";
private static final String ARRAY_END = "}";
private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END;
private static final String ARRAY_ELEMENT_SEPARATOR = ", ";
/**
* @Description:
* @方法名: isCheckedException</p>
* <p>@param : @param ex
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isCheckedException(Throwable ex) {
return !(ex instanceof RuntimeException || ex instanceof Error);
}
/**
* @Description:
* @方法名: isCompatibleWithThrowsClause</p>
* <p>@param : @param ex
* <p>@param : @param declaredExceptions
* @return boolean 返回类型</p>
* @throws
*/
@SuppressWarnings("unchecked")
public static boolean isCompatibleWithThrowsClause(Throwable ex, Class[] declaredExceptions) {
if (!isCheckedException(ex)) {
return true;
}
if (declaredExceptions != null) {
int i = 0;
while (i < declaredExceptions.length) {
if (declaredExceptions[i].isAssignableFrom(ex.getClass())) {
return true;
}
i++;
}
}
return false;
}
/**
* @Description:
* @方法名: isArray</p>
* <p>@param : @param obj
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isArray(Object obj) {
return (obj != null && obj.getClass().isArray());
}
/**
* @Description:
* @方法名: isEmpty</p>
* <p>@param : @param array
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
/**
* @Description:
* @方法名: containsElement</p>
* <p>@param : @param array
* <p>@param : @param element
* @return boolean 返回类型</p>
* @throws
*/
public static boolean containsElement(Object[] array, Object element) {
if (array == null) {
return false;
}
for (Object arrayEle : array) {
if (nullSafeEquals(arrayEle, element)) {
return true;
}
}
return false;
}
/**
* @Description:
* @方法名: addObjectToArray</p>
* <p>@param : @param array
* <p>@param : @param obj
* @return Object[] 返回类型</p>
* @throws
*/
@SuppressWarnings("unchecked")
public static Object[] addObjectToArray(Object[] array, Object obj) {
Class compType = Object.class;
if (array != null) {
compType = array.getClass().getComponentType();
}
else if (obj != null) {
compType = obj.getClass();
}
int newArrLength = (array != null ? array.length + 1 : 1);
Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength);
if (array != null) {
System.arraycopy(array, 0, newArr, 0, array.length);
}
newArr[newArr.length - 1] = obj;
return newArr;
}
/**
* @Description:
* @方法名: toObjectArray</p>
* <p>@param : @param source
* @return Object[] 返回类型</p>
* @throws
*/
@SuppressWarnings("unchecked")
public static Object[] toObjectArray(Object source) {
if (source instanceof Object[]) {
return (Object[]) source;
}
if (source == null) {
return new Object[0];
}
if (!source.getClass().isArray()) {
throw new IllegalArgumentException("Source is not an array: " + source);
}
int length = Array.getLength(source);
if (length == 0) {
return new Object[0];
}
Class wrapperType = Array.get(source, 0).getClass();
Object[] newArray = (Object[]) Array.newInstance(wrapperType, length);
for (int i = 0; i < length; i++) {
newArray[i] = Array.get(source, i);
}
return newArray;
}
/**
* @Description
* @方法名: nullSafeEquals</p>
* <p>@param : @param o1
* <p>@param : @param o2
* @return boolean 返回类型</p>
* @throws
*/
public static boolean nullSafeEquals(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
if (o1.equals(o2)) {
return true;
}
if (o1.getClass().isArray() && o2.getClass().isArray()) {
if (o1 instanceof Object[] && o2 instanceof Object[]) {
return Arrays.equals((Object[]) o1, (Object[]) o2);
}
if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
return Arrays.equals((boolean[]) o1, (boolean[]) o2);
}
if (o1 instanceof byte[] && o2 instanceof byte[]) {
return Arrays.equals((byte[]) o1, (byte[]) o2);
}
if (o1 instanceof char[] && o2 instanceof char[]) {
return Arrays.equals((char[]) o1, (char[]) o2);
}
if (o1 instanceof double[] && o2 instanceof double[]) {
return Arrays.equals((double[]) o1, (double[]) o2);
}
if (o1 instanceof float[] && o2 instanceof float[]) {
return Arrays.equals((float[]) o1, (float[]) o2);
}
if (o1 instanceof int[] && o2 instanceof int[]) {
return Arrays.equals((int[]) o1, (int[]) o2);
}
if (o1 instanceof long[] && o2 instanceof long[]) {
return Arrays.equals((long[]) o1, (long[]) o2);
}
if (o1 instanceof short[] && o2 instanceof short[]) {
return Arrays.equals((short[]) o1, (short[]) o2);
}
}
return false;
}
/**
* @Description:
* @方法名: nullSafeHashCode</p>
* <p>@param : @param obj
* @return int 返回类型</p>
* @throws
*/
public static int nullSafeHashCode(Object obj) {
if (obj == null) {
return 0;
}
if (obj.getClass().isArray()) {
if (obj instanceof Object[]) {
return nullSafeHashCode((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeHashCode((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeHashCode((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeHashCode((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeHashCode((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeHashCode((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeHashCode((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeHashCode((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeHashCode((short[]) obj);
}
}
return obj.hashCode();
}
/**
* @Description:
* @方法名: nullSafeHashCode</p>
* <p>@param : @param array
* @return int 返回类型</p>
* @throws
*/
public static int nullSafeHashCode(Object[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + nullSafeHashCode(array[i]);
}
return hash;
}
/**
* @Description:
* @方法名: nullSafeHashCode</p>
* <p>@param : @param array
* @return int 返回类型</p>
* @throws
*/
public static int nullSafeHashCode(boolean[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + hashCode(array[i]);
}
return hash;
}
/**
* @Description:
* @方法名: nullSafeHashCode</p>
* <p>@param : @param array
* @return int 返回类型</p>
* @throws
*/
public static int nullSafeHashCode(short[] array) {
if (array == null) {
return 0;
}
int hash = INITIAL_HASH;
int arraySize = array.length;
for (int i = 0; i < arraySize; i++) {
hash = MULTIPLIER * hash + array[i];
}
return hash;
}
/**
* @Description:
* @方法名: hashCode</p>
* <p>@param : @param bool
* @return int 返回类型</p>
* @throws
*/
public static int hashCode(boolean bool) {
return bool ? 1231 : 1237;
}
/**
* @Description:
* @方法名: hashCode</p>
* <p>@param : @param dbl
* @return int 返回类型</p>
* @throws
*/
public static int hashCode(double dbl) {
long bits = Double.doubleToLongBits(dbl);
return hashCode(bits);
}
/**
* @Description:
* @方法名: hashCode</p>
* <p>@param : @param flt
* @return int 返回类型</p>
* @throws
*/
public static int hashCode(float flt) {
return Float.floatToIntBits(flt);
}
/**
* @Description:
* @方法名: hashCode</p>
* <p>@param : @param lng
* @return int 返回类型</p>
* @throws
*/
public static int hashCode(long lng) {
return (int) (lng ^ (lng >>> 32));
}
/**
* @Description:
* @方法名: identityToString</p>
* <p>@param : @param obj
* @return String 返回类型</p>
* @throws
*/
public static String identityToString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return obj.getClass().getName() + "@" + getIdentityHexString(obj);
}
/**
* @Description:
* @方法名: getIdentityHexString</p>
* <p>@param : @param obj
* @return String 返回类型</p>
* @throws
*/
public static String getIdentityHexString(Object obj) {
return Integer.toHexString(System.identityHashCode(obj));
}
public static String getDisplayString(Object obj) {
if (obj == null) {
return EMPTY_STRING;
}
return null;
}
/**
* @Description:
* @方法名: nullSafeClassName</p>
* <p>@param : @param obj
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeClassName(Object obj) {
return (obj != null ? obj.getClass().getName() : NULL_STRING);
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param obj
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(Object obj) {
if (obj == null) {
return NULL_STRING;
}
if (obj instanceof String) {
return (String) obj;
}
if (obj instanceof Object[]) {
return nullSafeToString((Object[]) obj);
}
if (obj instanceof boolean[]) {
return nullSafeToString((boolean[]) obj);
}
if (obj instanceof byte[]) {
return nullSafeToString((byte[]) obj);
}
if (obj instanceof char[]) {
return nullSafeToString((char[]) obj);
}
if (obj instanceof double[]) {
return nullSafeToString((double[]) obj);
}
if (obj instanceof float[]) {
return nullSafeToString((float[]) obj);
}
if (obj instanceof int[]) {
return nullSafeToString((int[]) obj);
}
if (obj instanceof long[]) {
return nullSafeToString((long[]) obj);
}
if (obj instanceof short[]) {
return nullSafeToString((short[]) obj);
}
String str = obj.toString();
return (str != null ? str : EMPTY_STRING);
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(Object[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(String.valueOf(array[i]));
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(boolean[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(byte[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(char[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append("'").append(array[i]).append("'");
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(double[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(float[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(int[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(long[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
/**
* @Description:
* @方法名: nullSafeToString</p>
* <p>@param : @param array
* @return String 返回类型</p>
* @throws
*/
public static String nullSafeToString(short[] array) {
if (array == null) {
return NULL_STRING;
}
int length = array.length;
if (length == 0) {
return EMPTY_ARRAY;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i == 0) {
sb.append(ARRAY_START);
}
else {
sb.append(ARRAY_ELEMENT_SEPARATOR);
}
sb.append(array[i]);
}
sb.append(ARRAY_END);
return sb.toString();
}
public static String toString(Object obj){
return obj != null ? obj.toString() : "";
}
public static String toString(Object obj, String nullStr){
return obj != null ? obj.toString() : nullStr;
}
@SuppressWarnings("unchecked")
public static Object min(Comparable c1, Comparable c2){
if(c1 != null && c2 != null){
return c1.compareTo(c2) >= 1 ? c2 : c1;
}else {
return c1 == null ? c2 : c1;
}
}
@SuppressWarnings("unchecked")
public static Object max(Comparable c1, Comparable c2){
if(c1 != null && c2 != null){
return c1.compareTo(c2) < 0 ? c2 : c1;
}else {
return c1 == null ? c2 : c1;
}
}
}
|
GenericTypeAwarePropertyDescriptor |
java |
|
package cn.cd.sg.object.utils;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.MethodParameter;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
@SuppressWarnings("unchecked")
public class GenericTypeAwarePropertyDescriptor extends PropertyDescriptor{
private final Class beanClass;
private final Method readMethod;
private final Method writeMethod;
private final Class propertyEditorClass;
private volatile Set<Method> ambiguousWriteMethods;
private Class propertyType;
private MethodParameter writeMethodParameter;
public GenericTypeAwarePropertyDescriptor(Class beanClass, String propertyName,
Method readMethod, Method writeMethod, Class propertyEditorClass)
throws IntrospectionException {
super(propertyName, null, null);
this.beanClass = beanClass;
this.propertyEditorClass = propertyEditorClass;
Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod);
Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod);
if (writeMethodToUse == null && readMethodToUse != null) {
// Fallback: Original JavaBeans introspection might not have found matching setter
// method due to lack of bridge method resolution, in case of the getter using a
// covariant return type whereas the setter is defined for the concrete property type.
writeMethodToUse = ClassUtils.getMethodIfAvailable(this.beanClass,
"set" + StringUtils.capitalize(getName()), readMethodToUse.getReturnType());
}
this.readMethod = readMethodToUse;
this.writeMethod = writeMethodToUse;
if (this.writeMethod != null && this.readMethod == null) {
// Write method not matched against read method: potentially ambiguous through
// several overloaded variants, in which case an arbitrary winner has been chosen
// by the JDK's JavaBeans Introspector...
Set<Method> ambiguousCandidates = new HashSet<Method>();
for (Method method : beanClass.getMethods()) {
if (method.getName().equals(writeMethodToUse.getName()) &&
!method.equals(writeMethodToUse) && !method.isBridge()) {
ambiguousCandidates.add(method);
}
}
if (!ambiguousCandidates.isEmpty()) {
this.ambiguousWriteMethods = ambiguousCandidates;
}
}
}
@Override
public Method getReadMethod() {
return this.readMethod;
}
@Override
public Method getWriteMethod() {
return this.writeMethod;
}
public Method getWriteMethodForActualAccess() {
Set<Method> ambiguousCandidates = this.ambiguousWriteMethods;
if (ambiguousCandidates != null) {
this.ambiguousWriteMethods = null;
LogFactory.getLog(GenericTypeAwarePropertyDescriptor.class).warn("Invalid JavaBean property '" +
getName() + "' being accessed! Ambiguous write methods found next to actually used [" +
this.writeMethod + "]: " + ambiguousCandidates);
}
return this.writeMethod;
}
@Override
public Class getPropertyEditorClass() {
return this.propertyEditorClass;
}
@Override
public synchronized Class getPropertyType() {
if (this.propertyType == null) {
if (this.readMethod != null) {
this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass);
}
else {
MethodParameter writeMethodParam = getWriteMethodParameter();
if (writeMethodParam != null) {
this.propertyType = writeMethodParam.getParameterType();
}
else {
this.propertyType = super.getPropertyType();
}
}
}
return this.propertyType;
}
public synchronized MethodParameter getWriteMethodParameter() {
if (this.writeMethod == null) {
return null;
}
if (this.writeMethodParameter == null) {
this.writeMethodParameter = new MethodParameter(this.writeMethod, 0);
GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass);
}
return this.writeMethodParameter;
}
}
|
ClassUtils |
java |
|
package cn.cd.sg.object.utils;
import java.beans.Introspector;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cn.cd.sg.collection.utils.CollectionUtils;
import cn.cd.sg.reflect.utils.ReflectionUtils;
import cn.cd.sg.validate.utils.Validate;
@SuppressWarnings("unchecked")
public class ClassUtils {
/** Suffix for array class names: "[]" */
public static final String ARRAY_SUFFIX = "[]";
/** Prefix for internal array class names: "[" */
private static final String INTERNAL_ARRAY_PREFIX = "[";
/** Prefix for internal non-primitive array class names: "[L" */
private static final String NON_PRIMITIVE_ARRAY_PREFIX = "[L";
/** The package separator character '.' */
private static final char PACKAGE_SEPARATOR = '.';
/** The inner class separator character '$' */
private static final char INNER_CLASS_SEPARATOR = '$';
/** The CGLIB class separator character "$$" */
public static final String CGLIB_CLASS_SEPARATOR = "$$";
/** The ".class" file suffix */
public static final String CLASS_FILE_SUFFIX = ".class";
/**
* Map with primitive wrapper type as key and corresponding primitive
* type as value, for example: Integer.class -> int.class.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new HashMap<Class<?>, Class<?>>(8);
/**
* Map with primitive type as key and corresponding wrapper
* type as value, for example: int.class -> Integer.class.
*/
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new HashMap<Class<?>, Class<?>>(8);
/**
* Map with primitive type name as key and corresponding primitive
* type as value, for example: "int" -> "int.class".
*/
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap<String, Class<?>>(32);
/**
* Map with common "java.lang" class name as key and corresponding Class as value.
* Primarily for efficient deserialization of remote invocations.
*/
private static final Map<String, Class<?>> commonClassCache = new HashMap<String, Class<?>>(32);
static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);
for (Map.Entry<Class<?>, Class<?>> entry : primitiveWrapperTypeMap.entrySet()) {
primitiveTypeToWrapperMap.put(entry.getValue(), entry.getKey());
registerCommonClasses(entry.getKey());
}
Set<Class<?>> primitiveTypes = new HashSet<Class<?>>(32);
primitiveTypes.addAll(primitiveWrapperTypeMap.values());
primitiveTypes.addAll(Arrays.asList(
boolean[].class, byte[].class, char[].class, double[].class,
float[].class, int[].class, long[].class, short[].class));
primitiveTypes.add(void.class);
for (Class<?> primitiveType : primitiveTypes) {
primitiveTypeNameMap.put(primitiveType.getName(), primitiveType);
}
registerCommonClasses(Boolean[].class, Byte[].class, Character[].class, Double[].class,
Float[].class, Integer[].class, Long[].class, Short[].class);
registerCommonClasses(Number.class, Number[].class, String.class, String[].class,
Object.class, Object[].class, Class.class, Class[].class);
registerCommonClasses(Throwable.class, Exception.class, RuntimeException.class,
Error.class, StackTraceElement.class, StackTraceElement[].class);
}
/**
* Register the given common classes with the ClassUtils cache.
*/
private static void registerCommonClasses(Class<?>... commonClasses) {
for (Class<?> clazz : commonClasses) {
commonClassCache.put(clazz.getName(), clazz);
}
}
/**
* @Description: 获取当前 ClassLoader对象
* @方法名: getDefaultClassLoader</p>
* @return ClassLoader 返回类型</p>
* @throws
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
}
catch (Throwable ex) {
}
if (cl == null) {
cl = ClassUtils.class.getClassLoader();
}
return cl;
}
public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {
Thread currentThread = Thread.currentThread();
ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
if (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {
currentThread.setContextClassLoader(classLoaderToUse);
return threadContextClassLoader;
}
else {
return null;
}
}
@Deprecated
public static Class<?> forName(String name) throws ClassNotFoundException, LinkageError {
return forName(name, getDefaultClassLoader());
}
public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError {
Validate.notNull(name, "name 不能为 NULL ");
Class<?> clazz = resolvePrimitiveClassName(name);
if (clazz == null) {
clazz = commonClassCache.get(name);
}
if (clazz != null) {
return clazz;
}
// "java.lang.String[]" style arrays
if (name.endsWith(ARRAY_SUFFIX)) {
String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
Class<?> elementClass = forName(elementClassName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[Ljava.lang.String;" style arrays
if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
// "[[I" or "[[Ljava.lang.String;" style arrays
if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
Class<?> elementClass = forName(elementName, classLoader);
return Array.newInstance(elementClass, 0).getClass();
}
ClassLoader classLoaderToUse = classLoader;
if (classLoaderToUse == null) {
classLoaderToUse = getDefaultClassLoader();
}
try {
return classLoaderToUse.loadClass(name);
}
catch (ClassNotFoundException ex) {
int lastDotIndex = name.lastIndexOf('.');
if (lastDotIndex != -1) {
String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1);
try {
return classLoaderToUse.loadClass(innerClassName);
}
catch (ClassNotFoundException ex2) {
ex2.printStackTrace();
}
}
throw ex;
}
}
public static Class<?> resolveClassName(String className, ClassLoader classLoader) throws IllegalArgumentException {
try {
return forName(className, classLoader);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException("Cannot find class [" + className + "]", ex);
}
catch (LinkageError ex) {
throw new IllegalArgumentException(
"Error loading class [" + className + "]: problem with class file or dependent class.", ex);
}
}
public static Class<?> resolvePrimitiveClassName(String name) {
Class<?> result = null;
if (name != null && name.length() <= 8) {
result = primitiveTypeNameMap.get(name);
}
return result;
}
@Deprecated
public static boolean isPresent(String className) {
return isPresent(className, getDefaultClassLoader());
}
public static boolean isPresent(String className, ClassLoader classLoader) {
try {
forName(className, classLoader);
return true;
}
catch (Throwable ex) {
// Class or one of its dependencies is not present...
return false;
}
}
public static Class<?> getUserClass(Object instance) {
Validate.notNull(instance, "Instance 不能为 NULL ");
return getUserClass(instance.getClass());
}
public static Class<?> getUserClass(Class<?> clazz) {
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) {
return superClass;
}
}
return clazz;
}
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
Validate.notNull(clazz, "Class 不能为 NULL ");
ClassLoader target = clazz.getClassLoader();
if (target == null) {
return false;
}
ClassLoader cur = classLoader;
if (cur == target) {
return true;
}
while (cur != null) {
cur = cur.getParent();
if (cur == target) {
return true;
}
}
return false;
}
public static String getShortName(String className) {
Validate.hasLength(className, "Class name must not be empty");
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
int nameEndIndex = className.indexOf(CGLIB_CLASS_SEPARATOR);
if (nameEndIndex == -1) {
nameEndIndex = className.length();
}
String shortName = className.substring(lastDotIndex + 1, nameEndIndex);
shortName = shortName.replace(INNER_CLASS_SEPARATOR, PACKAGE_SEPARATOR);
return shortName;
}
public static String getShortName(Class<?> clazz) {
return getShortName(getQualifiedName(clazz));
}
public static String getShortNameAsProperty(Class<?> clazz) {
String shortName = ClassUtils.getShortName(clazz);
int dotIndex = shortName.lastIndexOf('.');
shortName = (dotIndex != -1 ? shortName.substring(dotIndex + 1) : shortName);
return Introspector.decapitalize(shortName);
}
public static String getClassFileName(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return className.substring(lastDotIndex + 1) + CLASS_FILE_SUFFIX;
}
public static String getPackageName(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return (lastDotIndex != -1 ? className.substring(0, lastDotIndex) : "");
}
public static String getQualifiedName(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
private static String getQualifiedNameForArray(Class<?> clazz) {
StringBuilder result = new StringBuilder();
while (clazz.isArray()) {
clazz = clazz.getComponentType();
result.append(ClassUtils.ARRAY_SUFFIX);
}
result.insert(0, clazz.getName());
return result.toString();
}
public static String getQualifiedMethodName(Method method) {
Validate.notNull(method, "Method must not be null");
return method.getDeclaringClass().getName() + "." + method.getName();
}
public static String getDescriptiveType(Object value) {
if (value == null) {
return null;
}
Class<?> clazz = value.getClass();
if (Proxy.isProxyClass(clazz)) {
StringBuilder result = new StringBuilder(clazz.getName());
result.append(" implementing ");
Class<?>[] ifcs = clazz.getInterfaces();
for (int i = 0; i < ifcs.length; i++) {
result.append(ifcs[i].getName());
if (i < ifcs.length - 1) {
result.append(',');
}
}
return result.toString();
}
else if (clazz.isArray()) {
return getQualifiedNameForArray(clazz);
}
else {
return clazz.getName();
}
}
public static boolean matchesTypeName(Class<?> clazz, String typeName) {
return (typeName != null &&
(typeName.equals(clazz.getName()) || typeName.equals(clazz.getSimpleName()) ||
(clazz.isArray() && typeName.equals(getQualifiedNameForArray(clazz)))));
}
public static boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) {
return (getConstructorIfAvailable(clazz, paramTypes) != null);
}
public static <T> Constructor<T> getConstructorIfAvailable(Class<T> clazz, Class<?>... paramTypes) {
Validate.notNull(clazz, "Class must not be null");
try {
return clazz.getConstructor(paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
}
public static boolean hasMethod(Class<?> clazz, String methodName, Class<?>... paramTypes) {
return (getMethodIfAvailable(clazz, methodName, paramTypes) != null);
}
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
Validate.notNull(clazz, "Class must not be null");
Validate.notNull(methodName, "Method name must not be null");
try {
return clazz.getMethod(methodName, paramTypes);
}
catch (NoSuchMethodException ex) {
return null;
}
}
public static int getMethodCountForName(Class<?> clazz, String methodName) {
Validate.notNull(clazz, "Class must not be null");
Validate.notNull(methodName, "Method name must not be null");
int count = 0;
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
if (methodName.equals(method.getName())) {
count++;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
count += getMethodCountForName(ifc, methodName);
}
if (clazz.getSuperclass() != null) {
count += getMethodCountForName(clazz.getSuperclass(), methodName);
}
return count;
}
public static boolean hasAtLeastOneMethodWithName(Class<?> clazz, String methodName) {
Validate.notNull(clazz, "Class must not be null");
Validate.notNull(methodName, "Method name must not be null");
Method[] declaredMethods = clazz.getDeclaredMethods();
for (Method method : declaredMethods) {
if (method.getName().equals(methodName)) {
return true;
}
}
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
if (hasAtLeastOneMethodWithName(ifc, methodName)) {
return true;
}
}
return (clazz.getSuperclass() != null && hasAtLeastOneMethodWithName(clazz.getSuperclass(), methodName));
}
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) {
Method specificMethod = null;
if (method != null && isOverridable(method, targetClass) &&
targetClass != null && !targetClass.equals(method.getDeclaringClass())) {
specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes());
}
return (specificMethod != null ? specificMethod : method);
}
private static boolean isOverridable(Method method, Class targetClass) {
if (Modifier.isPrivate(method.getModifiers())) {
return false;
}
if (Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers())) {
return true;
}
return getPackageName(method.getDeclaringClass()).equals(getPackageName(targetClass));
}
public static Method getStaticMethod(Class<?> clazz, String methodName, Class<?>... args) {
Validate.notNull(clazz, "Class must not be null");
Validate.notNull(methodName, "Method name must not be null");
try {
Method method = clazz.getMethod(methodName, args);
return Modifier.isStatic(method.getModifiers()) ? method : null;
}
catch (NoSuchMethodException ex) {
return null;
}
}
public static boolean isPrimitiveWrapper(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return primitiveWrapperTypeMap.containsKey(clazz);
}
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}
public static boolean isPrimitiveArray(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return (clazz.isArray() && clazz.getComponentType().isPrimitive());
}
public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
}
public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return (clazz.isPrimitive() && clazz != void.class? primitiveTypeToWrapperMap.get(clazz) : clazz);
}
public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
Validate.notNull(lhsType, "Left-hand side type must not be null");
Validate.notNull(rhsType, "Right-hand side type must not be null");
if (lhsType.isAssignableFrom(rhsType)) {
return true;
}
if (lhsType.isPrimitive()) {
Class resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);
if (resolvedPrimitive != null && lhsType.equals(resolvedPrimitive)) {
return true;
}
}
else {
Class resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);
if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) {
return true;
}
}
return false;
}
public static boolean isAssignableValue(Class<?> type, Object value) {
Validate.notNull(type, "Type must not be null");
return (value != null ? isAssignable(type, value.getClass()) : !type.isPrimitive());
}
public static String convertResourcePathToClassName(String resourcePath) {
Validate.notNull(resourcePath, "Resource path must not be null");
return resourcePath.replace('/', '.');
}
public static String convertClassNameToResourcePath(String className) {
Validate.notNull(className, "Class name must not be null");
return className.replace('.', '/');
}
public static String addResourcePathToPackagePath(Class<?> clazz, String resourceName) {
Validate.notNull(resourceName, "Resource name must not be null");
if (!resourceName.startsWith("/")) {
return classPackageAsResourcePath(clazz) + "/" + resourceName;
}
return classPackageAsResourcePath(clazz) + resourceName;
}
public static String classPackageAsResourcePath(Class<?> clazz) {
if (clazz == null) {
return "";
}
String className = clazz.getName();
int packageEndIndex = className.lastIndexOf('.');
if (packageEndIndex == -1) {
return "";
}
String packageName = className.substring(0, packageEndIndex);
return packageName.replace('.', '/');
}
public static String classNamesToString(Class... classes) {
return classNamesToString(Arrays.asList(classes));
}
public static String classNamesToString(Collection<Class> classes) {
if (CollectionUtils.isEmpty(classes)) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
for (Iterator<Class> it = classes.iterator(); it.hasNext(); ) {
Class clazz = it.next();
sb.append(clazz.getName());
if (it.hasNext()) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
public static Class[] getAllInterfaces(Object instance) {
Validate.notNull(instance, "Instance must not be null");
return getAllInterfacesForClass(instance.getClass());
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz) {
return getAllInterfacesForClass(clazz, null);
}
public static Class<?>[] getAllInterfacesForClass(Class<?> clazz, ClassLoader classLoader) {
Set<Class> ifcs = getAllInterfacesForClassAsSet(clazz, classLoader);
return ifcs.toArray(new Class[ifcs.size()]);
}
public static Set<Class> getAllInterfacesAsSet(Object instance) {
Validate.notNull(instance, "Instance must not be null");
return getAllInterfacesForClassAsSet(instance.getClass());
}
public static Set<Class> getAllInterfacesForClassAsSet(Class clazz) {
return getAllInterfacesForClassAsSet(clazz, null);
}
public static Set<Class> getAllInterfacesForClassAsSet(Class clazz, ClassLoader classLoader) {
Validate.notNull(clazz, "Class must not be null");
if (clazz.isInterface() && isVisible(clazz, classLoader)) {
return Collections.singleton(clazz);
}
Set<Class> interfaces = new LinkedHashSet<Class>();
while (clazz != null) {
Class<?>[] ifcs = clazz.getInterfaces();
for (Class<?> ifc : ifcs) {
interfaces.addAll(getAllInterfacesForClassAsSet(ifc, classLoader));
}
clazz = clazz.getSuperclass();
}
return interfaces;
}
public static Class<?> createCompositeInterface(Class<?>[] interfaces, ClassLoader classLoader) {
Validate.notEmpty(interfaces, "Interfaces must not be empty");
Validate.notNull(classLoader, "ClassLoader must not be null");
return Proxy.getProxyClass(classLoader, interfaces);
}
public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
}
//给一个接口 返回这个接口所有的实现类
public static List<Class> getAllClassForInterface(Class clazz){
List<Class> returnClassList = new ArrayList<Class>();
//判断是否是一个接口
if (clazz.isInterface()) {
//获取当前包名
String packageName = clazz.getPackage().getName();
try {
//获取包下面所有的类
List<Class> allClasses = getClasses(packageName);
//判断是否是同一接口
for (int i = 0; i < allClasses.size(); i++) {
if (clazz.isAssignableFrom(allClasses.get(i))) {
//本身就不加进去
if (!clazz.equals(allClasses.get(i))) {
returnClassList.add(allClasses.get(i));
}
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnClassList;
}
//从一个包中查找所有的类 在jar中不能查找
public static List<Class> getClasses(String packageName) throws ClassNotFoundException,IOException{
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
String path = packageName.replace(".", "/");
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while(resources.hasMoreElements()){
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
ArrayList<Class> classes = new ArrayList<Class>();
for(File directory : dirs){
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
public static List<Class> findClasses(File directory,String packageName) throws ClassNotFoundException{
List<Class> classes = new ArrayList<Class>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName+"." + file.getName()));
}else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName+"."+file.getName().substring(0,file.getName().length() - 6)));
}
}
return classes;
}
}
|
CachedIntrospectionResults |
java |
|
package cn.cd.sg.object.utils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import cn.cd.sg.string.utils.StringUtils;
@SuppressWarnings("unchecked")
public class CachedIntrospectionResults {
private static final Log logger = LogFactory.getLog(CachedIntrospectionResults.class);
/**
* Set of ClassLoaders that this CachedIntrospectionResults class will always
* accept classes from, even if the classes do not qualify as cache-safe.
*/
static final Set<ClassLoader> acceptedClassLoaders = Collections.synchronizedSet(new HashSet<ClassLoader>());
/**
* Map keyed by class containing CachedIntrospectionResults.
* Needs to be a WeakHashMap with WeakReferences as values to allow
* for proper garbage collection in case of multiple class loaders.
*/
static final Map<Class, Object> classCache = Collections.synchronizedMap(new WeakHashMap<Class, Object>());
/**
* Accept the given ClassLoader as cache-safe, even if its classes would
* not qualify as cache-safe in this CachedIntrospectionResults class.
* <p>This configuration method is only relevant in scenarios where the Spring
* classes reside in a 'common' ClassLoader (e.g. the system ClassLoader)
* whose lifecycle is not coupled to the application. In such a scenario,
* CachedIntrospectionResults would by default not cache any of the application's
* classes, since they would create a leak in the common ClassLoader.
* <p>Any <code>acceptClassLoader</code> call at application startup should
* be paired with a {@link #clearClassLoader} call at application shutdown.
* @param classLoader the ClassLoader to accept
*/
public static void acceptClassLoader(ClassLoader classLoader) {
if (classLoader != null) {
acceptedClassLoaders.add(classLoader);
}
}
/**
* Clear the introspection cache for the given ClassLoader, removing the
* introspection results for all classes underneath that ClassLoader,
* and deregistering the ClassLoader (and any of its children) from the
* acceptance list.
* @param classLoader the ClassLoader to clear the cache for
*/
public static void clearClassLoader(ClassLoader classLoader) {
if (classLoader == null) {
return;
}
synchronized (classCache) {
for (Iterator<Class> it = classCache.keySet().iterator(); it.hasNext();) {
Class beanClass = it.next();
if (isUnderneathClassLoader(beanClass.getClassLoader(), classLoader)) {
it.remove();
}
}
}
synchronized (acceptedClassLoaders) {
for (Iterator<ClassLoader> it = acceptedClassLoaders.iterator(); it.hasNext();) {
ClassLoader registeredLoader = it.next();
if (isUnderneathClassLoader(registeredLoader, classLoader)) {
it.remove();
}
}
}
}
/**
* Create CachedIntrospectionResults for the given bean class.
* <P>We don't want to use synchronization here. Object references are atomic,
* so we can live with doing the occasional unnecessary lookup at startup only.
* @param beanClass the bean class to analyze
* @return the corresponding CachedIntrospectionResults
* @throws BeansException in case of introspection failure
*/
static CachedIntrospectionResults forClass(Class beanClass) throws BeansException {
CachedIntrospectionResults results;
Object value = classCache.get(beanClass);
if (value instanceof Reference) {
Reference ref = (Reference) value;
results = (CachedIntrospectionResults) ref.get();
}
else {
results = (CachedIntrospectionResults) value;
}
if (results == null) {
// On JDK 1.5 and higher, it is almost always safe to cache the bean class...
// The sole exception is a custom BeanInfo class being provided in a non-safe ClassLoader.
boolean fullyCacheable =
ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader()) ||
isClassLoaderAccepted(beanClass.getClassLoader());
if (fullyCacheable || !ClassUtils.isPresent(beanClass.getName() + "BeanInfo", beanClass.getClassLoader())) {
results = new CachedIntrospectionResults(beanClass, fullyCacheable);
classCache.put(beanClass, results);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Not strongly caching class [" + beanClass.getName() + "] because it is not cache-safe");
}
results = new CachedIntrospectionResults(beanClass, true);
classCache.put(beanClass, new WeakReference<CachedIntrospectionResults>(results));
}
}
return results;
}
/**
* Check whether this CachedIntrospectionResults class is configured
* to accept the given ClassLoader.
* @param classLoader the ClassLoader to check
* @return whether the given ClassLoader is accepted
* @see #acceptClassLoader
*/
private static boolean isClassLoaderAccepted(ClassLoader classLoader) {
// Iterate over array copy in order to avoid synchronization for the entire
// ClassLoader check (avoiding a synchronized acceptedClassLoaders Iterator).
ClassLoader[] acceptedLoaderArray =
acceptedClassLoaders.toArray(new ClassLoader[acceptedClassLoaders.size()]);
for (ClassLoader registeredLoader : acceptedLoaderArray) {
if (isUnderneathClassLoader(classLoader, registeredLoader)) {
return true;
}
}
return false;
}
/**
* Check whether the given ClassLoader is underneath the given parent,
* that is, whether the parent is within the candidate's hierarchy.
* @param candidate the candidate ClassLoader to check
* @param parent the parent ClassLoader to check for
*/
private static boolean isUnderneathClassLoader(ClassLoader candidate, ClassLoader parent) {
if (candidate == null) {
return false;
}
if (candidate == parent) {
return true;
}
ClassLoader classLoaderToCheck = candidate;
while (classLoaderToCheck != null) {
classLoaderToCheck = classLoaderToCheck.getParent();
if (classLoaderToCheck == parent) {
return true;
}
}
return false;
}
/** The BeanInfo object for the introspected bean class */
private final BeanInfo beanInfo;
/** PropertyDescriptor objects keyed by property name String */
private final Map<String, PropertyDescriptor> propertyDescriptorCache;
/**
* Create a new CachedIntrospectionResults instance for the given class.
* @param beanClass the bean class to analyze
* @throws BeansException in case of introspection failure
*/
private CachedIntrospectionResults(Class beanClass, boolean cacheFullMetadata) throws BeansException {
try {
if (logger.isTraceEnabled()) {
logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]");
}
this.beanInfo = Introspector.getBeanInfo(beanClass);
// Immediately remove class from Introspector cache, to allow for proper
// garbage collection on class loader shutdown - we cache it here anyway,
// in a GC-friendly manner. In contrast to CachedIntrospectionResults,
// Introspector does not use WeakReferences as values of its WeakHashMap!
Class classToFlush = beanClass;
do {
Introspector.flushFromCaches(classToFlush);
classToFlush = classToFlush.getSuperclass();
}
while (classToFlush != null);
if (logger.isTraceEnabled()) {
logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]");
}
this.propertyDescriptorCache = new LinkedHashMap<String, PropertyDescriptor>();
// This call is slow so we do it once.
PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (Class.class.equals(beanClass) && "classLoader".equals(pd.getName())) {
// Ignore Class.getClassLoader() method - nobody needs to bind to that
continue;
}
if (logger.isTraceEnabled()) {
logger.trace("Found bean property '" + pd.getName() + "'" +
(pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") +
(pd.getPropertyEditorClass() != null ?
"; editor [" + pd.getPropertyEditorClass().getName() + "]" : ""));
}
if (cacheFullMetadata) {
pd = buildGenericTypeAwarePropertyDescriptor(beanClass, pd);
}
this.propertyDescriptorCache.put(pd.getName(), pd);
}
}
catch (IntrospectionException ex) {
throw new FatalBeanException("Failed to obtain BeanInfo for class [" + beanClass.getName() + "]", ex);
}
}
BeanInfo getBeanInfo() {
return this.beanInfo;
}
Class getBeanClass() {
return this.beanInfo.getBeanDescriptor().getBeanClass();
}
PropertyDescriptor getPropertyDescriptor(String name) {
PropertyDescriptor pd = this.propertyDescriptorCache.get(name);
if (pd == null && StringUtils.hasLength(name)) {
// Same lenient fallback checking as in PropertyTypeDescriptor...
pd = this.propertyDescriptorCache.get(name.substring(0, 1).toLowerCase() + name.substring(1));
if (pd == null) {
pd = this.propertyDescriptorCache.get(name.substring(0, 1).toUpperCase() + name.substring(1));
}
}
return (pd == null || pd instanceof GenericTypeAwarePropertyDescriptor ? pd :
buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd));
}
PropertyDescriptor[] getPropertyDescriptors() {
PropertyDescriptor[] pds = new PropertyDescriptor[this.propertyDescriptorCache.size()];
int i = 0;
for (PropertyDescriptor pd : this.propertyDescriptorCache.values()) {
pds[i] = (pd instanceof GenericTypeAwarePropertyDescriptor ? pd :
buildGenericTypeAwarePropertyDescriptor(getBeanClass(), pd));
i++;
}
return pds;
}
private PropertyDescriptor buildGenericTypeAwarePropertyDescriptor(Class beanClass, PropertyDescriptor pd) {
try {
return new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(),
pd.getWriteMethod(), pd.getPropertyEditorClass());
}
catch (IntrospectionException ex) {
throw new FatalBeanException("Failed to re-introspect class [" + beanClass.getName() + "]", ex);
}
}
}
|
BeanUtils |
java |
|
package cn.cd.sg.object.utils;
import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.core.MethodParameter;
import cn.cd.sg.reflect.utils.ReflectionUtils;
import cn.cd.sg.string.utils.StringUtils;
import cn.cd.sg.validate.utils.Validate;
public class BeanUtils {
private static final Log logger = LogFactory.getLog(BeanUtils.class);
private static final Map<Class<?>, Boolean> unknownEditorTypes = Collections
.synchronizedMap(new WeakHashMap<Class<?>, Boolean>());
/**
* @Description: 通过 Class 来实例化 对象
* @param : @param clazz
* @param : @throws BeanInstantiationException 设定文件
* @return T 返回类型</p>
* @throws
*/
public static <T> T instantiate(Class<T> clazz)
throws BeanInstantiationException {
Validate.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz,
"Specified class is an interface");
}
try {
return clazz.newInstance();
} catch (InstantiationException ex) {
throw new BeanInstantiationException(clazz,
"Is it an abstract class?", ex);
} catch (IllegalAccessException ex) {
throw new BeanInstantiationException(clazz,
"Is the constructor accessible?", ex);
}
}
/**
* @Description: ()
* @方法名: instantiateClass</p>
* @param : @param clazz
* @param : @throws BeanInstantiationException 设定文件
* @return T 返回类型</p>
* @throws
*/
public static <T> T instantiateClass(Class<T> clazz)
throws BeanInstantiationException {
Validate.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz,
"Specified class is an interface");
}
try {
return instantiateClass(clazz.getDeclaredConstructor());
} catch (NoSuchMethodException ex) {
throw new BeanInstantiationException(clazz,
"No default constructor found", ex);
}
}
/**
* @Description:通过 反射获取 class构造 来实例化 对象
* @方法名: instantiateClass</p>
* @param : @param ctor
* @param : @param args
* @param : @throws BeanInstantiationException 设定文件
* @return T 返回类型</p>
* @throws
*/
public static <T> T instantiateClass(Constructor<T> ctor, Object... args)
throws BeanInstantiationException {
Validate.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
} catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),
"Is it an abstract class?", ex);
} catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),
"Is the constructor accessible?", ex);
} catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),
"Illegal arguments for constructor", ex);
} catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor.getDeclaringClass(),
"Constructor threw exception", ex.getTargetException());
}
}
/**
* @Description: 根据 Class对象 方法名 和参数类型来获取 方法
* @方法名: findMethod</p>
* @param : @param clazz class对象
* @param : @param methodName 方法名
* @param : @param paramTypes 参数类型
* @return Method 返回类型</p>
* @throws
*/
public static Method findMethod(Class<?> clazz, String methodName,Class<?>... paramTypes) {
try {
return clazz.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
return findDeclaredMethod(clazz, methodName, paramTypes);
}
}
/**
* @Description:
* @方法名: findDeclaredMethod</p>
* @param : @param clazz
* @param : @param methodName
* @param : @param paramTypes
* @param : @return 设定文件
* @return Method 返回类型</p>
* @throws
*/
public static Method findDeclaredMethod(Class<?> clazz, String methodName,
Class<?>[] paramTypes) {
try {
return clazz.getDeclaredMethod(methodName, paramTypes);
} catch (NoSuchMethodException ex) {
if (clazz.getSuperclass() != null) {
return findDeclaredMethod(clazz.getSuperclass(), methodName,
paramTypes);
}
return null;
}
}
/**
* @Description:
* @方法名: findMethodWithMinimalParameters</p>
* @param : @param clazz
* @param : @param methodName
* @param : @return
* @param : @throws IllegalArgumentException 设定文件
* @return Method 返回类型</p>
* @throws
*/
public static Method findMethodWithMinimalParameters(Class<?> clazz,
String methodName) throws IllegalArgumentException {
Method targetMethod = findMethodWithMinimalParameters(clazz.getMethods(), methodName);
if (targetMethod == null) {
targetMethod = findDeclaredMethodWithMinimalParameters(clazz,methodName);
}
return targetMethod;
}
/**
* @Description:
* @方法名: findDeclaredMethodWithMinimalParameters</p>
* @param : @param clazz
* @param : @param methodName
* @param : @return
* @param : @throws IllegalArgumentException 设定文件
* @return Method 返回类型</p>
* @throws
*/
public static Method findDeclaredMethodWithMinimalParameters(
Class<?> clazz, String methodName) throws IllegalArgumentException {
Method targetMethod = findMethodWithMinimalParameters(clazz
.getDeclaredMethods(), methodName);
if (targetMethod == null && clazz.getSuperclass() != null) {
targetMethod = findDeclaredMethodWithMinimalParameters(clazz
.getSuperclass(), methodName);
}
return targetMethod;
}
/**
* @Description:
* @方法名: findMethodWithMinimalParameters</p>
* @param : @param methods
* @param : @param methodName
* @param : @return
* @param : @throws IllegalArgumentException 设定文件
* @return Method 返回类型</p>
* @throws
*/
public static Method findMethodWithMinimalParameters(Method[] methods,
String methodName) throws IllegalArgumentException {
Method targetMethod = null;
int numMethodsFoundWithCurrentMinimumArgs = 0;
for (Method method : methods) {
if (method.getName().equals(methodName)) {
int numParams = method.getParameterTypes().length;
if (targetMethod == null
|| numParams < targetMethod.getParameterTypes().length) {
targetMethod = method;
numMethodsFoundWithCurrentMinimumArgs = 1;
} else {
if (targetMethod.getParameterTypes().length == numParams) {
numMethodsFoundWithCurrentMinimumArgs++;
}
}
}
}
if (numMethodsFoundWithCurrentMinimumArgs > 1) {
throw new IllegalArgumentException(
"Cannot resolve method '"
+ methodName
+ "' to a unique method. Attempted to resolve to overloaded method with "
+ "the least number of parameters, but there were "
+ numMethodsFoundWithCurrentMinimumArgs
+ " candidates.");
}
return targetMethod;
}
/**
* @Description:
* @方法名: resolveSignature</p>
* @param : @param signature
* @param : @param clazz
* @param : @return 设定文件
* @return Method 返回类型</p>
* @throws
*/
public static Method resolveSignature(String signature, Class<?> clazz) {
Validate.hasText(signature, "'signature' must not be empty");
Validate.notNull(clazz, "Class must not be null");
int firstParen = signature.indexOf("(");
int lastParen = signature.indexOf(")");
if (firstParen > -1 && lastParen == -1) {
throw new IllegalArgumentException("Invalid method signature '"
+ signature + "': expected closing ')' for args list");
} else if (lastParen > -1 && firstParen == -1) {
throw new IllegalArgumentException("Invalid method signature '"
+ signature + "': expected opening '(' for args list");
} else if (firstParen == -1 && lastParen == -1) {
return findMethodWithMinimalParameters(clazz, signature);
} else {
String methodName = signature.substring(0, firstParen);
String[] parameterTypeNames = StringUtils
.commaDelimitedListToStringArray(signature.substring(
firstParen + 1, lastParen));
Class<?>[] parameterTypes = new Class[parameterTypeNames.length];
for (int i = 0; i < parameterTypeNames.length; i++) {
String parameterTypeName = parameterTypeNames[i].trim();
try {
parameterTypes[i] = ClassUtils.forName(parameterTypeName,
clazz.getClassLoader());
} catch (Throwable ex) {
throw new IllegalArgumentException(
"Invalid method signature: unable to resolve type ["
+ parameterTypeName + "] for argument " + i
+ ". Root cause: " + ex);
}
}
return findMethod(clazz, methodName, parameterTypes);
}
}
/**
* @Description:
* @方法名: getPropertyDescriptors</p>
* @param : @param clazz
* @param : @return
* @param : @throws BeansException 设定文件
* @return PropertyDescriptor[] 返回类型</p>
* @throws
*/
public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz)
throws BeansException {
CachedIntrospectionResults cr = CachedIntrospectionResults.forClass(clazz);
return cr.getPropertyDescriptors();
}
/**
* @Description:
* @方法名: getPropertyDescriptor</p>
* @param : @param clazz
* @param : @param propertyName
* @param : @return
* @param : @throws BeansException 设定文件
* @return PropertyDescriptor 返回类型</p>
* @throws
*/
public static PropertyDescriptor getPropertyDescriptor(Class<?> clazz,
String propertyName) throws BeansException {
CachedIntrospectionResults cr = CachedIntrospectionResults
.forClass(clazz);
return cr.getPropertyDescriptor(propertyName);
}
/**
* @Description:
* @方法名: findPropertyForMethod</p>
* @param : @param method
* @param : @throws BeansException 设定文件
* @return PropertyDescriptor 返回类型</p>
* @throws
*/
public static PropertyDescriptor findPropertyForMethod(Method method)
throws BeansException {
Validate.notNull(method, "Method must not be null");
PropertyDescriptor[] pds = getPropertyDescriptors(method
.getDeclaringClass());
for (PropertyDescriptor pd : pds) {
if (method.equals(pd.getReadMethod())
|| method.equals(pd.getWriteMethod())) {
return pd;
}
}
return null;
}
/**
* @Description:
* @方法名: findEditorByConvention</p>
* @param : @param targetType
* @return PropertyEditor 返回类型</p>
* @throws
*/
public static PropertyEditor findEditorByConvention(Class<?> targetType) {
if (targetType == null || targetType.isArray()
|| unknownEditorTypes.containsKey(targetType)) {
return null;
}
ClassLoader cl = targetType.getClassLoader();
if (cl == null) {
try {
cl = ClassLoader.getSystemClassLoader();
if (cl == null) {
return null;
}
} catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not access system ClassLoader: " + ex);
}
return null;
}
}
String editorName = targetType.getName() + "Editor";
try {
Class<?> editorClass = cl.loadClass(editorName);
if (!PropertyEditor.class.isAssignableFrom(editorClass)) {
if (logger.isWarnEnabled()) {
logger
.warn("Editor class ["
+ editorName
+ "] does not implement [java.beans.PropertyEditor] interface");
}
unknownEditorTypes.put(targetType, Boolean.TRUE);
return null;
}
return (PropertyEditor) instantiateClass(editorClass);
} catch (ClassNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("No property editor [" + editorName
+ "] found for type " + targetType.getName()
+ " according to 'Editor' suffix convention");
}
unknownEditorTypes.put(targetType, Boolean.TRUE);
return null;
}
}
/**
* @Description:
* @方法名: findPropertyType</p>
* @param : @param propertyName
* @param : @param beanClasses
* @param : @return 设定文件
* @return Class<?> 返回类型</p>
* @throws
*/
public static Class<?> findPropertyType(String propertyName,
Class<?>[] beanClasses) {
if (beanClasses != null) {
for (Class<?> beanClass : beanClasses) {
PropertyDescriptor pd = getPropertyDescriptor(beanClass,
propertyName);
if (pd != null) {
return pd.getPropertyType();
}
}
}
return Object.class;
}
/**
* @Description:
* @方法名: getWriteMethodParameter</p>
* @param : @param pd
* @return MethodParameter 返回类型</p>
* @throws
*/
public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) {
if (pd instanceof GenericTypeAwarePropertyDescriptor) {
return new MethodParameter(
((GenericTypeAwarePropertyDescriptor) pd)
.getWriteMethodParameter());
} else {
return new MethodParameter(pd.getWriteMethod(), 0);
}
}
/**
* @Description
* @方法名: isSimpleProperty</p>
* @param : @param clazz
* @param : @return 设定文件
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isSimpleProperty(Class<?> clazz) {
Validate.notNull(clazz, "Class must not be null");
return isSimpleValueType(clazz)
|| (clazz.isArray() && isSimpleValueType(clazz
.getComponentType()));
}
/**
* @Description:
* @方法名: isSimpleValueType</p>
* @param : @param clazz
* @param : @return 设定文件
* @return boolean 返回类型</p>
* @throws
*/
public static boolean isSimpleValueType(Class<?> clazz) {
return ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum()
|| CharSequence.class.isAssignableFrom(clazz)
|| Number.class.isAssignableFrom(clazz)
|| Date.class.isAssignableFrom(clazz)
|| clazz.equals(URI.class) || clazz.equals(URL.class)
|| clazz.equals(Locale.class) || clazz.equals(Class.class);
}
/**
* @Description:
* @方法名: copyProperties</p>
* @param : @param source
* @param : @param target
* @param : @throws BeansException 设定文件
* @return void 返回类型</p>
* @throws
*/
public static void copyProperties(Object source, Object target)
throws BeansException {
copyProperties(source, target, null, null);
}
/**
* @Description:
* @方法名: copyProperties</p>
* @param : @param source
* @param : @param target
* @param : @param editable
* @param : @throws BeansException 设定文件
* @return void 返回类型</p>
* @throws
*/
public static void copyProperties(Object source, Object target,
Class<?> editable) throws BeansException {
copyProperties(source, target, editable, null);
}
/**
* @Description:
* @方法名: copyProperties</p>
* @param : @param source
* @param : @param target
* @param : @param ignoreProperties
* @param : @throws BeansException 设定文件
* @return void 返回类型</p>
* @throws
*/
public static void copyProperties(Object source, Object target,
String[] ignoreProperties) throws BeansException {
copyProperties(source, target, null, ignoreProperties);
}
private static void copyProperties(Object source, Object target,
Class<?> editable, String[] ignoreProperties) throws BeansException {
Validate.notNull(source, "Source must not be null");
Validate.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class ["
+ target.getClass().getName()
+ "] not assignable to Editable class ["
+ editable.getName() + "]");
}
actualEditable = editable;
}
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = (ignoreProperties != null) ? Arrays
.asList(ignoreProperties) : null;
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null
&& (ignoreProperties == null || (!ignoreList
.contains(targetPd.getName())))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source
.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass()
.getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass()
.getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
} catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy properties from source to target",ex);
}
}
}
}
}
}
|
JSONUtils |
java |
|
package cn.cd.sg.json.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@SuppressWarnings("unchecked")
public class JSONUtils {
/**
* 描述 : (将List对象序列化为JSON文本 )
* 方法名: toJSONString
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:40:41
* @param <T>
* @param list
* @return
* @return :String
*/
public static String toJSONString(List list) {
JSONArray js = JSONArray.fromObject(list);
return js.toString();
}
/**
* 描述 : (将对象序列化为JSON文本 )
* 方法名: toJSONString
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:44:38
* @param object
* @return
* @return :String
*/
public static String toJSONString(Object object) {
JSONObject jo = JSONObject.fromObject(object);
return jo.toString();
}
/**
* 描述 : (将JSON对象数组序列化为JSON文本 )
* 方法名: toJSONString
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:46:07
* @param ja
* @return
* @return :String
*/
public static String toJSONString(JSONArray ja) {
return ja.toString();
}
/**
* 描述 : (将JSON对象序列化为JSON文本
* 方法名: toJSONString
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:52:23
* @param jo
* @return
* @return :String
*/
public static String toJSONString(JSONObject jo) {
return jo.toString();
}
/**
* 描述 : (将对象转换为List对象 )
* 方法名: toArrayList
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:53:58
* @param object
* @return
* @return :List
*/
public static List toArrayList(Object object) {
List arrList = new ArrayList();
JSONArray ja = JSONArray.fromObject(object);
Iterator<?> iterator = ja.iterator();
while (iterator.hasNext()) {
JSONObject jo = (JSONObject) iterator.next();
Iterator<?> keys = jo.keys();
while (keys.hasNext()) {
Object key = keys.next();
Object value = jo.get(key);
arrList.add(value);
}
}
return arrList;
}
/**
* 描述 : ( 将对象转换为Collection对象 )
* 方法名: toCollection
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:55:17
* @param object
* @return
* @return :Collection
*/
public static Collection toCollection(Object object) {
JSONArray ja = JSONArray.fromObject(object);
return JSONArray.toCollection(ja);
}
/**
* 描述 : (将对象转换为JSON对象数组 )
* 方法名: toJSONArray
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:58:35
* @param object
* @return
* @return :JSONArray
*/
public static JSONArray toJSONArray(Object object) {
return JSONArray.fromObject(object);
}
/**
* 描述 : (将对象转换为JSON对象 )
* 方法名: toJSONObject
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:00:40
* @param object
* @return
* @return :JSONObject
*/
public static JSONObject toJSONObject(Object object) {
return JSONObject.fromObject(object);
}
/**
* 描述 : (将一个json字符串 转换成list对象 )
* 方法名: json2List
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:02:22
* @param jsonStr
* @return
* @return :List<Map<String,Object>>
*/
public static List<Map<String, Object>> json2List(String jsonStr) {
JSONArray ja = JSONArray.fromObject(jsonStr);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = ja.iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(json2Map(json2));
}
return list;
}
/**
* 描述 : (将一个json数组转换成list对象 )
* 方法名: json2List
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:07:07
* @param ja
* @return
* @return :List<Map<String,Object>>
*/
public static List<Map<String, Object>> json2List(JSONArray ja) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = ja.iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(json2Map(json2));
}
return list;
}
/**
* 描述 : (将一个json字符串转换成Map对象 )
* 方法名: json2Map
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:07:22
* @param jsonStr
* @return
* @return :Map<String,Object>
*/
public static Map<String, Object> json2Map(String jsonStr) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject jo = JSONObject.fromObject(jsonStr);
for (Object key : jo.keySet()) {
Object value = jo.get(key);
if (value instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> iterator = ((JSONArray) value).iterator();
while (iterator.hasNext()) {
JSONObject jo2 = iterator.next();
list.add(json2Map(jo2.toString()));
}
map.put(key.toString(), value);
} else {
map.put(key.toString(), value);
}
}
return map;
}
/**
* 将一个json对象转换成Map对象
*
* @param jo
* @return
*/
public static Map<String, Object> json2Map(JSONObject jo) {
Map<String, Object> map = new HashMap<String, Object>();
for (Object key : jo.keySet()) {
Object value = jo.get(key);
if (value instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> iterator = ((JSONArray) value).iterator();
while (iterator.hasNext()) {
JSONObject jo2 = iterator.next();
list.add(json2Map(jo2.toString()));
}
map.put(key.toString(), value);
} else {
map.put(key.toString(), value);
}
}
return map;
}
/**
* 描述 : (MAP转换 成 json字符串)
* 方法名: map2Json
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:16:46
* @param map
* @return
* @return :String
*/
public static String map2Json(Map map){
if (null == map) {
return null;
}
JSONObject jo = JSONObject.fromObject(map);
return jo.toString();
}
/**
* 描述 : (通过HTTP url获取JSON数据 )
* 方法名: getListByUrl
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:17:11
* @param url
* @return
* @return :List<Map<String,Object>>
*/
public static List<Map<String, Object>> getListByUrl(String url) {
StringBuilder builder = null;
try {
InputStream in = new URL(url).openStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
builder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return json2List(builder.toString());
}
/**
* 描述 : (通过HTTP url获取JSON数据 )
* 方法名: getMapByUrl
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:17:24
* @param url
* @return
* @return :Map<String,Object>
*/
public static Map<String, Object> getMapByUrl(String url) {
StringBuilder builder = null;
try {
InputStream in = new URL(url).openStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line = "";
builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return json2Map(builder.toString());
}
/**
* 描述 : (将对象转换为HashMap )
* 方法名: toHashMap
* 创建人:孙刚
* 创建时间:2014-2-8 下午06:17:37
* @param object
* @return
* @return :HashMap
*/
public static HashMap toHashMap(Object object) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jo = JSONUtils.toJSONObject(object);
Iterator iterator = jo.keys();
while (iterator.hasNext()) {
Object obj = iterator.next();
String key = "";
if (obj instanceof String) {
key = (String) obj;
}
Object value = jo.get(key);
map.put(key, value);
}
return map;
}
/**
* 将对象转换为List<Map<String,Object>> 返回非实体类型(Map<String,Object>)的List
*
* @return
*/
public static List<Map<String, Object>> toList(Object object) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
JSONArray ja = JSONArray.fromObject(object);
for (Object obj : ja) {
if (obj instanceof JSONObject) {
JSONObject jo = (JSONObject) obj;
Map<String, Object> map = new HashMap<String, Object>();
Iterator iterator = jo.keys();
while (iterator.hasNext()) {
Object o = iterator.next();
String key = "";
if (o instanceof String) {
key = (String) o;
}
Object value = jo.get(key);
map.put(key, value);
}
list.add(map);
}
}
return list;
}
/**
* 将JSON对象数组转换为传入类型的List
*
* @param <T>
* @param ja
* @param clazz
* @return
*/
@SuppressWarnings("deprecation")
public static <T> List<T> toList(JSONArray ja, Class<T> clazz) {
return JSONArray.toList(ja, clazz);
}
/**
* 将对象转换为传入类型的List
*
* @param <T>
* @param object
* @param clazz
* @return
*/
@SuppressWarnings("deprecation")
public static <T> List<T> toList(Object object, Class<T> clazz) {
JSONArray ja = JSONArray.fromObject(object);
return JSONArray.toList(ja, clazz);
}
/**
* 将JSON对象转换为传入类型的对象
*
* @param <T>
* @param jo
* @param clazz
* @return
*/
@SuppressWarnings("static-access")
public static <T> T toBean(JSONObject jo, Class<T> clazz) {
return (T) jo.toBean(jo, clazz);
}
/**
* 将将对象转换为传入类型的对象
*
* @param <T>
* @param object
* @param clazz
* @return
*/
@SuppressWarnings("static-access")
public static <T> T toBean(Object object, Class<T> clazz) {
JSONObject jo = JSONObject.fromObject(object);
return (T) jo.toBean(jo, clazz);
}
/***
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>
* 泛型T 代表主实体类型
* @param <D>
* 泛型D 代表从实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailName
* 从实体类在主实体类中的属性名称
* @param detailClass
* 从实体类型
* @return
*/
@SuppressWarnings("unused")
public static <T, D> T toBean(String jsonString, Class<T> mainClass,
String detailName, Class<D> detailClass) {
JSONObject jo = JSONObject.fromObject(jsonString);
JSONArray ja = (JSONArray) jo.get(detailName);
T mainEntity = JSONUtils.toBean(jo, mainClass);
List<D> detailList = JSONUtils.toList(ja, detailClass);
try {
org.apache.commons.beanutils.BeanUtils.setProperty(mainEntity, detailName, detailClass);
} catch (Exception e) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/**
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>>泛型T 代表主实体类型
* @param <D1>泛型D1 代表从实体类型
* @param <D2>泛型D2 代表从实体类型
* @param jsonStringJSON文本
* @param maiinClass
* 主实体类型
* @param detailName1
* 从实体类在主实体类中的属性
* @param detailClass1
* 从实体类型
* @param detailName2
* 从实体类在主实体类中的属性
* @param detailClass2
* 从实体类型
* @return
*/
@SuppressWarnings("unused")
public static <T, D1, D2> T toBean(String jsonString, Class<T> maiinClass,
String detailName1, Class<D1> detailClass1, String detailName2,
Class<D2> detailClass2) {
JSONObject jo = JSONObject.fromObject(jsonString);
JSONArray ja1 = (JSONArray) jo.get(detailName1);
JSONArray ja2 = (JSONArray) jo.get(detailName2);
T mainEntity = JSONUtils.toBean(jo, maiinClass);
List<D1> detailList1 = JSONUtils.toList(ja1, detailClass1);
List<D2> detailList2 = JSONUtils.toList(ja2, detailClass2);
try {
BeanUtils.setProperty(mainEntity, detailName1, detailClass1);
BeanUtils.setProperty(mainEntity, detailName2, detailClass2);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/***
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>泛型T 代表主实体类型
* @param <D1>泛型D1 代表从实体类型
* @param <D2>泛型D2 代表从实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailName1
* 从实体类在主实体类中的属性
* @param detailClass1
* 从实体类型
* @param detailName2
* 从实体类在主实体类中的属性
* @param detailClass2
* 从实体类型
* @param detailName3
* 从实体类在主实体类中的属性
* @param detailClass3
* 从实体类型
* @return
*/
public static <T, D1, D2, D3> T toBean(String jsonString,
Class<T> mainClass, String detailName1, Class<D1> detailClass1,
String detailName2, Class<D2> detailClass2, String detailName3,
Class<D3> detailClass3) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
List<D1> detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
List<D2> detailList2 = JSONUtils.toList(jsonArray2, detailClass2);
List<D3> detailList3 = JSONUtils.toList(jsonArray3, detailClass3);
try {
BeanUtils.setProperty(mainEntity, detailName1, detailList1);
BeanUtils.setProperty(mainEntity, detailName2, detailList2);
BeanUtils.setProperty(mainEntity, detailName3, detailList3);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/***
* 将JSON文本反序列化为主从关系的实体
*
* @param <T>
* 主实体类型
* @param jsonString
* JSON文本
* @param mainClass
* 主实体类型
* @param detailClass
* 存放了多个从实体在主实体中属性名称和类型
* @return
*/
public static <T> T toBean(String jsonString, Class<T> mainClass,
HashMap<String, Class> detailClass) {
JSONObject jsonObject = JSONObject.fromObject(jsonString);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
for (Object key : detailClass.keySet()) {
try {
Class value = (Class) detailClass.get(key);
BeanUtils.setProperty(mainEntity, key.toString(), value);
} catch (Exception ex) {
throw new RuntimeException("主从关系JSON反序列化实体失败!");
}
}
return mainEntity;
}
}
|
GenericsUtils |
java |
|
package cn.cd.sg.generics.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class GenericsUtils {
/**
* 通过反射,获得指定类的父类的泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承范型父类
* @param index 泛型参数所在索引,从0开始.
* @return 范型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();//得到泛型父类
//如果没有实现ParameterizedType接口,即不支持泛型,直接返回Object.class
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
//返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends DaoSupport<Buyer,Contact>就返回Buyer和Contact类型
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射,获得指定类的父类的第一个泛型参数的实际类型. 如BuyerServiceBean extends DaoSupport<Buyer>
*
* @param clazz clazz 需要反射的类,该类必须继承泛型父类
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz,0);
}
/**
* 通过反射,获得方法返回值泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method, int index) {
Type returnType = method.getGenericReturnType();
if(returnType instanceof ParameterizedType){
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
if (index >= typeArguments.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)typeArguments[index];
}
return Object.class;
}
/**
* 通过反射,获得方法返回值第一个泛型参数的实际类型. 如: public Map<String, Buyer> getNames(){}
*
* @param Method method 方法
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getMethodGenericReturnType(Method method) {
return getMethodGenericReturnType(method, 0);
}
/**
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @param int index 第几个输入参数
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length ||index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
Type genericParameterType = genericParameterTypes[index];
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for(Type parameterArgType : parameterArgTypes){
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* 通过反射,获得方法输入参数第一个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
*
* @param Method method 方法
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("unchecked")
public static List<Class> getMethodGenericParameterTypes(Method method) {
return getMethodGenericParameterTypes(method, 0);
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field, int index) {
Type genericFieldType = field.getGenericType();
if(genericFieldType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericFieldType;
Type[] fieldArgTypes = aType.getActualTypeArguments();
if (index >= fieldArgTypes.length || index < 0) {
throw new RuntimeException("你输入的索引"+ (index<0 ? "不能小于0" : "超出了参数的总数"));
}
return (Class)fieldArgTypes[index];
}
return Object.class;
}
/**
* 通过反射,获得Field泛型参数的实际类型. 如: public Map<String, Buyer> names;
*
* @param Field field 字段
* @param int index 泛型参数所在索引,从0开始.
* @return 泛型参数的实际类型, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回<code>Object.class</code>
*/
@SuppressWarnings("unchecked")
public static Class getFieldGenericType(Field field) {
return getFieldGenericType(field, 0);
}
}
|
WriteToFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
/**
* 多种方式写文件
*/
public class WriteToFileUtils {
/**
* 以字节为单位写文件。适合于写二进制文件。如图片等
* @param fileName 文件名
*/
public static void writeFileByBytes(String fileName){
File file = new File(fileName);
OutputStream out= null;
try {
// 打开文件输出流
out = new FileOutputStream(file);
String content = "文件内容:\n1,The First line;\n2,The second line.";
byte[] bytes = content.getBytes();
//写入文件
out.write(bytes);
System.out.println("写文件" + file.getAbsolutePath() + "成功!");
} catch (IOException e){
System.out.println("写文件" + file.getAbsolutePath() + "失败!");
e.printStackTrace();
} finally {
if (out != null){
try {
//关闭输出文件流
out.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位写文件。
* @param fileName 文件名
*/
public static void writeFileByChars(String fileName){
File file = new File(fileName);
Writer writer = null;
try {
//打开文件输出流
writer = new OutputStreamWriter(new FileOutputStream(file));
String content = "文件内容:\n1,The First line;\n2,The second line.";
writer.write(content);
System.out.println("写文件" + file.getAbsolutePath() + "成功!");
} catch (IOException e){
System.out.println("写文件" + file.getAbsolutePath() + "失败!");
e.printStackTrace();
} finally {
if (writer != null){
try {
//关闭输出文件流
writer.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位写文件
* @param fileName 文件名
*/
public static void writeFileByLines(String fileName){
File file = new File(fileName);
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileOutputStream(file));
//写字符串
writer.println("文件内容:");
//能写各种基本类型数据
writer.print(true);
writer.print(155);
//换行
writer.println();
//写入文件
writer.flush();
System.out.println("写文件" + file.getAbsolutePath() + "成功!");
} catch (FileNotFoundException e) {
System.out.println("写文件" + file.getAbsolutePath() + "失败!");
e.printStackTrace();
} finally {
if (writer != null){
//关闭输出文件流
writer.close();
}
}
}
public static void main(String[] args) {
String fileName = "c:/temp/tempfile0.txt";
WriteToFileUtils.writeFileByBytes(fileName);
fileName = "c:/temp/tempfile1.txt";
WriteToFileUtils.writeFileByChars(fileName);
fileName = "c:/temp/tempfile2.txt";
WriteToFileUtils.writeFileByLines(fileName);
}
}
|
StatisFileChars |
|
|
package cn.cd.sg.file.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamTokenizer;
/**
* 使用StreamTokenizer来统计文件中的字符数
* StreamTokenizer 类获取输入流并将其分析为“标记”,允许一次读取一个标记。
* 分析过程由一个表和许多可以设置为各种状态的标志控制。
* 该流的标记生成器可以识别标识符、数字、引用的字符串和各种注释样式。
*
* 默认情况下,StreamTokenizer认为下列内容是Token: 字母、数字、除C和C++注释符号以外的其他符号。
* 如符号"/"不是Token,注释后的内容也不是,而"\"是Token。单引号和双引号以及其中的内容,只能算是一个Token。
* 统计文章字符数的程序,不是简单的统计Token数就万事大吉,因为字符数不等于Token。按照Token的规定,
* 引号中的内容就算是10页也算一个Token。如果希望引号和引号中的内容都算作Token,应该调用下面的代码:
* st.ordinaryChar('\'');
* st.ordinaryChar('\"');
*/
public class StatisFileChars {
/**
* 统计字符数
* @param fileName 文件名
* @return 字符数
*/
public static long statis(String fileName) {
FileReader fileReader = null;
try {
fileReader = new FileReader(fileName);
//创建分析给定字符流的标记生成器
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
fileReader));
//ordinaryChar方法指定字符参数在此标记生成器中是“普通”字符。
//下面指定单引号、双引号和注释符号是普通字符
st.ordinaryChar('\'');
st.ordinaryChar('\"');
st.ordinaryChar('/');
String s;
int numberSum = 0;
int wordSum = 0;
int symbolSum = 0;
int total = 0;
//nextToken方法读取下一个Token.
//TT_EOF指示已读到流末尾的常量。
while (st.nextToken() != StreamTokenizer.TT_EOF) {
//在调用 nextToken 方法之后,ttype字段将包含刚读取的标记的类型
switch (st.ttype) {
//TT_EOL指示已读到行末尾的常量。
case StreamTokenizer.TT_EOL:
break;
//TT_NUMBER指示已读到一个数字标记的常量
case StreamTokenizer.TT_NUMBER:
//如果当前标记是一个数字,nval字段将包含该数字的值
s = String.valueOf((st.nval));
System.out.println(s);
numberSum += s.length();
break;
//TT_WORD指示已读到一个文字标记的常量
case StreamTokenizer.TT_WORD:
//如果当前标记是一个文字标记,sval字段包含一个给出该文字标记的字符的字符串
s = st.sval;
wordSum += s.length();
break;
default:
//如果以上3中类型都不是,则为英文的标点符号
s = String.valueOf((char) st.ttype);
symbolSum += s.length();
}
}
System.out.println("sum of number = " + numberSum);
System.out.println("sum of word = " + wordSum);
System.out.println("sum of symbol = " + symbolSum);
total = symbolSum + numberSum + wordSum;
System.out.println("Total = " + total);
return total;
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
String fileName = "c:/temp/newTemp.txt";
StatisFileChars.statis(fileName);
}
}
|
PDFFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.pdfbox.pdfparser.PDFParser;
import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;
import com.lowagie.text.Cell;
import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
/**
* 很多应用程序要求动态生成 PDF 文档。这类应用程序包括银行生成用于电子邮件投递的客户报表,到读者购买特定图书章节并以 PDF 格式接收这些文档。例子罗列下去是很多的。在本文中,将使用 iText Java 库生成 PDF 文档,并引导您完成一个示例应用程序,以使您能够更好地理解和使用 iText。
iText 是 Lowagie.com 站点(请参阅 参考资料)免费提供的 Java 库。iText 库的功能很强大,支持 HTML、RTF 和 XML 文档的生成,此外还能够生成 PDF 文档。可以从多种字体中选择文档中所使用的字体。同时,iText 的结构允许使用相同的代码生成以上任意类型的文档。
* http://www.lowagie.com/iText/
* iText API:近距离观察
com.lowagie.text.Document 是生成 PDF 的主要的类。它是需要使用的第一个类。一旦开始创建文档,将需要一个写入器向文档中写入内容。com.lowagie.text.pdf.PdfWriter 就是一个 PDF 写入器。下面列出了通常需要使用的类:
com.lowagie.text.Paragraph —— 这个类表示一个缩进的段落。
com.lowagie.text.Chapter —— 这个类表示 PDF 文档中的章节。使用 Paragraph 作为题目并使用 int 作为章节号码来创建它。
com.lowagie.text.Font —— 这个类包含了全部的字体规范,例如字体、大小、样式和颜色。各种字体都在这个类中声明为静态常数。
com.lowagie.text.List —— 这个类表示一个列表,按顺序包含许多 ListItems。
com.lowagie.text.Table —— 这个类表示包含单元格的表,单元格有序地排列在矩阵中。
*/
public class PDFFileUtils {
//private static Logger logger = Logger.getLogger(PDFFileUtils.class);
/**
* 写PDF文件,展示了PDF文档、章节、小节、字体、段落、表格、列表的使用
* 最后展示如何使用写入中文。
* @param fileName
*/
public void writePDF(String fileName) throws DocumentException {
File file = new File(fileName);
FileOutputStream out = null;
try {
//(1)实例化文档对象
//第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
//(2)创建写入器
//第一个参数是对文档对象的引用,第二个参数是输出的文件,将out和document连接起来
out = new FileOutputStream(file);
//PdfWriter writer = PdfWriter.getInstance(document, out);
//打开文档准备写入内容
document.open();
//(3)下面创建章节对象
//首先创建段落对象,作为章节的标题。FontFactory用于指定段落的字体。
Font font = FontFactory.getFont(FontFactory.HELVETICA,
18, Font.BOLDITALIC, new Color(0, 0, 255));
Paragraph chapter1_title = new Paragraph("Chapter 1",font);
//创建了一个章节对象,标题为"Chapter 1"
Chapter chapter1 = new Chapter(chapter1_title, 1);
//将编号级别设为 0 就不会在页面上显示章节编号
chapter1.setNumberDepth(0);
//(4)创建小节对象
//创建小节对象的标题
font = FontFactory.getFont(FontFactory.HELVETICA, 16,
Font.BOLD, new Color(255, 0, 0));
Paragraph section1_title1 = new Paragraph("Section 1 of Chapter 1", font);
//创建一个小节对象,标题为"This is Section 1 in Chapter 1",属于chapter1。
Section section1 = chapter1.addSection(section1_title1);
//(5)往小节中写文本内容
Paragraph text = new Paragraph("This is the first text in section 1 of chapter 1.");
section1.add(text);
text = new Paragraph("Following is a 5×5 table:");
section1.add(text);
//(6)往小节中写表格
//创建表格对象
Table table = null;
table = new Table(5, 5);
//设置表格边框颜色
table.setBorderColor(new Color(220, 255, 100));
//设置单元格的边距间隔等
table.setPadding(1);
table.setSpacing(1);
table.setBorderWidth(1);
//单元格对象
Cell cell = null;
//添加表头信息
for (int colNum=0; colNum<5; colNum++){
cell = new Cell("header-" + colNum);
cell.setHeader(true);
table.addCell(cell);
}
table.endHeaders();
//添加表的内容
for (int rowNum=1; rowNum<5; rowNum++){
for (int colNum=0; colNum<5; colNum++){
cell= new Cell("value-" + rowNum + "-" + colNum);
table.addCell(cell);
}
}
//将表格对象添加到小节对象中
section1.add(table);
//(7)添加列表
// 列表包含一定数量的 ListItem。可以对列表进行编号,也可以不编号。
// 将第一个参数设置为 true 表明想创建一个进行编号的列表;
// 第二个参数设置为true表示列表采用字母进行编号,为false则用数字进行编号;
// 第三个参数为列表内容与编号之间的距离。
List list = new List(true, false, 20);
ListItem item = new ListItem("First item of list;");
list.add(item);
item = new ListItem("Second item of list;");
list.add(item);
item = new ListItem("Third item of list.");
list.add(item);
//将列表对象添加到小节对象中
section1.add(list);
//(8)添加中文
//允许在PDF中写入中文,将字体文件放在classPath中。
//simfang.ttf是仿宋的字体文件
BaseFont bfChinese = null;
bfChinese = BaseFont.createFont("宋体", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//中文大小为20,加粗
font = new Font(bfChinese, 20, Font.BOLD);
text = new Paragraph("PDF中文测试", font);
section1.add(text);
//(9)将章节对象加入到文档中
document.add(chapter1);
//(10)关闭文档
document.close();
System.out.println("PDF文件生成成功,PDF文件名:" + file.getAbsolutePath());
} catch (Exception ee) {
System.out.println("PDF文件"+ file.getAbsolutePath() + "生成失败!" + ee);
ee.printStackTrace();
} finally {
if (out != null){
try {
//关闭输出文件流
out.close();
} catch (IOException e1) {
}
}
}
}
/**
* 读PDF文件,使用了pdfbox开源项目,新的版本已经支持中文了。
* 上www.pdfbox.org下载读PDF的jar包
* @param fileName
*/
public void readPDF(String fileName) {
File file = new File(fileName);
FileInputStream in = null;
try {
in = new FileInputStream(fileName);
//新建一个PDF解析器对象
PDFParser parser = new PDFParser(in);
//对PDF文件进行解析
parser.parse();
//获取解析后得到的PDF文档对象
PDDocument pdfdocument = parser.getPDDocument();
//新建一个PDF文本剥离器
PDFTextStripper stripper = new PDFTextStripper();
//从PDF文档对象中剥离文本
String result = stripper.getText(pdfdocument);
System.out.println("PDF文件" + file.getAbsolutePath() + "的文本内容如下:");
System.out.println(result);
} catch (Exception e) {
System.out.println("读取PDF文件"+ file.getAbsolutePath() + "生失败!" + e);
e.printStackTrace();
} finally {
if (in != null){
try {
in.close();
} catch (IOException e1) {
}
}
}
}
public static void main(String[] args) {
PDFFileUtils pdf = new PDFFileUtils();
String fileName = "D:/FusionCharts1.pdf";
try {
pdf.writePDF(fileName);
} catch (DocumentException e) {
e.printStackTrace();
}
//pdf.readPDF(fileName);
}
}
|
MoveFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
/**
* 移动文件或目录
*/
public class MoveFileUtils {
/**
* 移动单个文件,不覆盖已存在的目标文件
* @param srcFileName 待移动的原文件名
* @param destFileName 目标文件名
* @return 文件移动成功返回true,否则返回false
*/
public static boolean moveFile(String srcFileName, String destFileName){
//默认为不覆盖目标文件
return MoveFileUtils.moveFile(srcFileName, destFileName, false);
}
/**
* 移动单个文件
* @param srcFileName 待移动的原文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 文件移动成功返回true,否则返回false
*/
public static boolean moveFile(String srcFileName,
String destFileName, boolean overlay){
//判断原文件是否存在
File srcFile = new File(srcFileName);
if (!srcFile.exists()){
System.out.println("移动文件失败:原文件" + srcFileName + "不存在!");
return false;
} else if (!srcFile.isFile()){
System.out.println("移动文件失败:" + srcFileName + "不是一个文件!");
return false;
}
File destFile = new File(destFileName);
//如果目标文件存在
if (destFile.exists()){
//如果允许文件覆盖
if (overlay){
//删除已存在的目标文件,无论目标文件是目录还是单个文件
System.out.println("目标文件已存在,准备删除它!");
if(!DeleteFileUtils.delete(destFileName)){
System.out.println("移动文件失败:删除目标文件" + destFileName + "失败!");
return false;
}
} else {
System.out.println("移动文件失败:目标文件" + destFileName + "已存在!");
return false;
}
} else {
if (!destFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建目录
System.out.println("目标文件所在目录不存在,准备创建它!");
if(!destFile.getParentFile().mkdirs()){
System.out.println("移动文件失败:创建目标文件所在的目录失败!" );
return false;
}
}
}
//移动原文件至目标文件
if (srcFile.renameTo(destFile)){
System.out.println("移动单个文件" + srcFileName + "至" + destFileName + "成功!");
return true;
} else {
System.out.println("移动单个文件" + srcFileName + "至" + destFileName + "失败!");
return true;
}
}
/**
* 移动目录,不覆盖已存在的目标目录
* @param srcDirName 待移动的原目录名
* @param destDirName 目标目录名
* @return 目录移动成功返回true,否则返回false
*/
public static boolean moveDirectory(String srcDirName, String destDirName){
//默认为不覆盖目标文件
return MoveFileUtils.moveDirectory(srcDirName, destDirName, false);
}
/**
* 移动目录。
* @param srcDirName 待移动的原目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目论存在,是否覆盖
* @return 目录移动成功返回true,否则返回false
*/
public static boolean moveDirectory(String srcDirName,
String destDirName, boolean overlay){
//判断原目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()){
System.out.println("移动目录失败:原目录" + srcDirName + "不存在!");
return false;
} else if (!srcDir.isDirectory()){
System.out.println("移动目录失败:" + srcDirName + "不是一个目录!");
return false;
}
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
if (!destDirName.endsWith(File.separator)){
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
//如果目标文件夹存在,
if (destDir.exists()){
if (overlay){
//允许覆盖则删除已存在的目标目录
System.out.println("目标目录已存在,准备删除它!");
if (!DeleteFileUtils.delete(destDirName)){
System.out.println("移动目录失败:删除目标目录" + destDirName + "失败!");
}
} else {
System.out.println("移动目录失败:目标目录" + destDirName + "已存在!");
return false;
}
} else {
//创建目标目录
System.out.println("目标目录不存在,准备创建它!");
if(!destDir.mkdirs()){
System.out.println("移动目录失败:创建目标目录失败!" );
return false;
}
}
boolean flag = true;
//移动原目录下的文件和子目录到目标目录下
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) {
//移动子文件
if (files[i].isFile()){
flag = MoveFileUtils.moveFile(files[i].getAbsolutePath(),
destDirName + files[i].getName(), overlay);
if (!flag){
break;
}
}
//移动子目录
else if (files[i].isDirectory()){
flag = MoveFileUtils.moveDirectory(files[i].getAbsolutePath(),
destDirName + files[i].getName(), overlay);
if (!flag){
break;
}
}
}
if (!flag){
System.out.println("移动目录" + srcDirName + "至" + destDirName+ "失败!");
return false;
}
// 删除原目录
if (DeleteFileUtils.deleteDirectory(srcDirName)){
System.out.println("移动目录" + srcDirName + "至" + destDirName+ "成功!");
return true;
} else {
System.out.println("移动目录" + srcDirName + "至" + destDirName+ "失败!");
return false;
}
}
public static void main(String[] args) {
//移动单个文件,如果目标文件存在,则替换
String srcFileName = "C:/temp/temp.txt";
String destFileName = "C:/tempbak/temp_bak.txt.";
MoveFileUtils.moveFile(srcFileName, destFileName, true);
System.out.println();
//移动目录,如果目标目录存在,则不覆盖
String srcDirName = "C:/temp";
String destDirName = "C:/tempbak";
MoveFileUtils.moveDirectory(srcDirName, destDirName);
}
}
|
ListFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
import java.io.FilenameFilter;
public class ListFileUtils {
/**
* 这是一个内部类,实现了FilenameFilter接口,用于过滤文件
*/
static class MyFilenameFilter implements FilenameFilter{
//文件名后缀
private String suffix = "";
public MyFilenameFilter(String surfix){
this.suffix = surfix;
}
public boolean accept(File dir, String name) {
//如果文件名以surfix指定的后缀相同,便返回true,否则返回false
if (new File(dir, name).isFile()){
return name.endsWith(suffix);
}else{
//如果是文件夹,则直接返回true
return true;
}
}
}
/**
* 列出目录下所有文件包括子目录的文件路径
* @param dirName 文件夹的文件路径
*/
public static void listAllFiles(String dirName){
//如果dir不以文件分隔符结尾,自动添加文件分隔符。
if (!dirName.endsWith(File.separator)){
dirName = dirName + File.separator;
}
File dirFile = new File(dirName);
//如果dir对应的文件不存在,或者不是一个文件夹,则退出
if (!dirFile.exists() || (!dirFile.isDirectory())){
System.out.println("List失败!找不到目录:" + dirName);
return;
}
//列出源文件夹下所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){
System.out.println(files[i].getAbsolutePath() + " 是文件!");
}else if (files[i].isDirectory()){
System.out.println(files[i].getAbsolutePath() + " 是目录!");
ListFileUtils.listAllFiles(files[i].getAbsolutePath());
}
}
}
/**
* 列出目录中通过文件名过滤器过滤后的文件。
* @param filter 文件名过滤器对象
* @param dirName 目录名
*/
public static void listFilesByFilenameFilter(FilenameFilter filter, String dirName){
//如果dir不以文件分隔符结尾,自动添加文件分隔符。
if (!dirName.endsWith(File.separator)){
dirName = dirName + File.separator;
}
File dirFile = new File(dirName);
//如果dir对应的文件不存在,或者不是一个文件夹,则退出
if (!dirFile.exists() || (!dirFile.isDirectory())){
System.out.println("List失败!找不到目录:" + dirName);
return;
}
//列出源文件夹下所有文件(包括子目录)
File[] files = dirFile.listFiles(filter);
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){
System.out.println(files[i].getAbsolutePath() + " 是文件!");
}else if (files[i].isDirectory()){
System.out.println(files[i].getAbsolutePath() + " 是目录!");
ListFileUtils.listFilesByFilenameFilter(filter, files[i].getAbsolutePath());
}
}
}
public static void main(String[] args) {
String dir = "C:/temp";
// System.out.println((dir + "目录下的内容: "));
// ListFileUtil.listAllFiles(dir);
//
// System.out.println();
// System.out.println("经过过滤器过滤后的内容:");
// //新建一个文件名过滤器。参数为".txt"
// FilenameFilter myFilenameFilter = new ListFileUtil.MyFilenameFilter(".txt");
// ListFileUtil.listFilesByFilenameFilter(myFilenameFilter, dir);
//
String[] t = new File(dir).list();
for (int i=0; i<t.length; i++){
System.out.println(t[i]);
}
}
}
|
FileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import org.apache.log4j.Logger;
public class FileUtils {
private final static Logger logger = Logger.getLogger(FileUtils.class);
/**
* 判断源文件是否存在且是否为文件
* @param sourceFile
* @return
*/
public static boolean isExistsSource(String sourceFile) {
File srcFile = new File(sourceFile);
if (!srcFile.exists()) {
logger.info("复制文件失败:源文件" + sourceFile + "不存在!");
return false;
} else if (!srcFile.isFile()) {
logger.info("复制文件失败:" + sourceFile + "不是一个文件!");
return false;
}
return true;
}
/**
* 判断目标文件所在目录是否存在
* @param targetFile
* @return
*/
public static boolean isExistsTargetDir(String targetFile) {
File destFile = new File(targetFile);
if (!destFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建目录
logger.info("目标文件所在的目录不存在:" + destFile.getParentFile());
//创建目录
//destFile.getParentFile().mkdirs();
return false;
}
return true;
}
/**
* 判断该文件是否存在
* @param fileName - 文件名称
* @param path - 目录
* @return - 是否存在
*/
public static boolean isFileExist(String fileName, String path){
File file = new File(getDoPath(path)+fileName);
return file.exists();
}
/**
* 复制单个文件
*
* @param srcFileName
* 待复制的文件名
* @param destFileName
* 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName) {
//源文件是否存在
isExistsSource(srcFileName);
//目标文件所在目录是否存在
isExistsTargetDir(destFileName);
// 准备复制文件
int byteread = 0;// 读取的位数
InputStream in = null;
OutputStream out = null;
File srcFile = new File(srcFileName);
File destFile = new File(destFileName);
try {
// 打开原文件
in = new FileInputStream(srcFile);
// 打开连接到目标文件的输出流
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
// 一次读取1024个字节,当byteread为-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
// 将读取的字节写入输出流
out.write(buffer, 0, byteread);
}
logger.info("复制文件" + srcFileName + "至" + destFileName + "成功!");
return true;
} catch (Exception e) {
logger.error("复制文件失败:" + e.getMessage());
return false;
} finally {
// 关闭输入输出流,注意先关闭输出流,再关闭输入流
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error("复制文件关闭流时出错:" + e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error("复制文件关闭流时出错:" + e.getMessage());
}
}
}
}
//==============================================================================
//
//删除文件夹
// 此为调用java基础类,利用递归实现方式
// 除此之外用apache io包FileUtils也很方便,以下为apache io包实现方式:
// org.apache.commons.io.FileUtils.deleteDirectory(f);//删除目录
// org.apache.tools.ant.util.FileUtils.delete(f);//删除文件
//
//==============================================================================
/**
* 删除文件夹:文件夹下的所有文件
* @param filepath 格式形如:d://1//2/3//4
* 即为删除4这个文件夹
* @return
*/
public static boolean removeFile(String filepath) {
try {
File f = new File(filepath);
if(f.exists() && f.isDirectory()) { //判断是文件还是目录
if(f.listFiles().length == 0) { //若目录下没有文件则直接删除
f.delete();
} else { //若有则把文件放进数组,并判断是否有下级目录
File childFile[]=f.listFiles();
int i = f.listFiles().length;
for(int j = 0; j < i; j++) {
if(childFile[j].isDirectory()) {
//递归调用del方法并取得子目录路径
removeFile(childFile[j].getAbsolutePath());
}
childFile[j].delete(); //删除文件
}
//删除文件夹下的子文件后再删除主文件夹
f.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("删除文件出错!");
return false;
}
return true;
}
/**
* 传递一个路径和文件名称,删除该文件
* @param fileName - 文件名称
* @param path - 路径
* @return - 是否删除成功
*/
public static boolean removeFile(String fileName, String path){
boolean flag = false;
if (isFileExist(fileName, path)) {
File file = new File(getDoPath(path)+fileName);
flag = file.delete();
}
return flag;
}
/**
* 删除当前文件
* @param file - 要删除的文件
* @return 是否删除成功
*/
public static boolean removeFile(File file){
boolean flag = false;
if (file != null && file.exists()) {
flag = file.delete();
}
return flag;
}
/**
* 传入一个文件名,得到这个文件名称的后缀 包含 .
* @param fileName - 文件名
* @return
*/
public static String getSuffixContainPoint(String fileName){
int index = fileName.lastIndexOf(".");
if (index != -1) {
String suffix = fileName.substring(index);//后缀
return suffix;
}else {
return null;
}
}
/**
* 传入一个文件名,得到这个文件名称的后缀 不包含 .
* @param fileName - 文件名
* @return
*/
public static String getSuffixUnContainPoint(String fileName){
int index = fileName.lastIndexOf(".");
if (index != -1) {
String suffix = fileName.substring(index + 1);//后缀
return suffix;
} else {
return null;
}
}
/**
* 利用uuid产生一个随机的name
* @param fileName 文件名
* @return
*/
public static String getRandomName(String fileName){
String randomName = UUID.randomUUID().toString();
//如果文件没有后缀名 默认就是给添加 后缀 txt
return getNewFileName(fileName, randomName , "txt");
}
/**
* 用当前日期、时间和1000以内的随机数组合成的文件名称
* @param fileName - 文件名
* @return
*/
public static String getNumberFileName(String fileName){
SimpleDateFormat format = new SimpleDateFormat("yyMMddhhmmss");
int rand = new Random().nextInt(1000);
String numberFileName = format.format(new Date()) + rand;
return getNewFileName(fileName, numberFileName, "txt");
}
/**
* 传递一个文件名称和一个新名称,组合成一个新的带后缀文件名
* 当传递的文件名没有后缀,会添加默认的后缀
* @param fileName - 文件名称
* @param newFileName - 新文件名称
* @param nullSuffix - 为没有后缀的文件所添加的后缀 如果没有 可传递一个默认的后缀名 eq .txt
* @return
*/
public static String getNewFileName(String fileName,String newFileName,String nullSuffix){
String suffix = getSuffixContainPoint(fileName);
if (suffix != null) {
newFileName += suffix;
}else {
newFileName = newFileName.concat(".").concat(nullSuffix);
}
return newFileName;
}
/**
*
* @param pathName
* @return
*/
public static boolean isBlankForPath(String pathName) {
boolean flag = false;
String[] letters = new String[] { "/", "\\", ":", "*", "?", "\"", " <",
">", " ¦", "%20", "#", "$", "%" };
for (int i = 0; i < letters.length; i++) {
if (pathName.indexOf(letters[i]) != -1) {
flag = true;
} else {
flag = false;
}
}
return flag;
}
/**
* 处理后的系统文件路径
* @param path
* @return
*/
public static String getDoPath(String path){
path = path.replace("\\", "/");
String lastChar = path.substring(path.length() - 1);
if (!"/".equals(lastChar)) {
path += "/";
}
return path;
}
/**
* 创建指定的path路径目录
* @param path - 目录、路径
* @return
*/
public static boolean mkDir(String path){
File file = null;
try {
file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
}catch (Exception e) {
logger.error("创建文件失败..错误如下:");
e.printStackTrace();
}finally{
file = null;
}
return false;
}
/**
* 功能:提取文件名的后缀
*
* @param fileName
* @return
*/
@SuppressWarnings("unused")
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
/**
* 功能:将文件拷贝到指定位置
*
* @param src
* @param dst
*/
private static final int BUFFER_SIZE = 16 * 1024;
@SuppressWarnings("unused")
private static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
FileFiend |
java |
|
/**
* Program : FileFiend.java
* Author : niehai
* Create : 2009-4-23 ����02:20:51
*
* Copyright 2007 by Embedded Internet Solutions Inc.,
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Embedded Internet Solutions Inc.("Confidential Information").
* You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement
* you entered into with Embedded Internet Solutions Inc.
*
*/
package cn.cd.sg.file.utils;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
public class FileFiend {
public static final String FILE_SEPARATOR = System
.getProperty("file.separator");
private final static Logger logger = Logger.getLogger(FileFiend.class);
/**
* 删除指定的文件夹。
*
* @param directoryPath
* @return 是否成功 成功=true.
*/
public static boolean deleteDirectory(String directoryPath) {
File file;
File[] files;
file = new File(directoryPath);
if (file != null) {
if (file.exists() && file.isDirectory()) {
files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].exists()) {
if (files[i].isDirectory()) {
deleteDirectory(files[i].getPath());
} else if (files[i].isFile()) {
boolean isHad = files[i].delete();
if (!isHad) {
logger
.info("delete file <<<<<<<faile>>>>>>>:"
+ files[i]);
return false;
}
}
}
}
file.delete();
}
} else if (!file.exists() && file.isDirectory()) {
logger.debug("directory do not exists!:" + directoryPath
+ " at _File.deleteDirectory()");
return true;
}
} else {
logger.debug("file Object is null!:path=" + directoryPath);
return false;
}
return true;
}
/**
* 删除指定的文件
*
* @param filePath
* @return int:1=delete sucess;0=delete <<<<<<<faile>>>>>>>;2=no such
* file;
*/
public static int deleteFile(String filePath) {
File file = new File(filePath);
if (file != null) {
if (file.exists()) {
if (file.delete()) {
logger.debug("delete the file sucess: " + filePath);
return 1;
} else {
logger.debug("delete the file <<<<<<<faile>>>>>>>: "
+ filePath);
return 0;
}
} else {
logger.debug("this file do not existe :" + filePath);
return 2;
}
} else {
logger.debug("file Object is null!:path=" + filePath);
return 2;
}
}
/**
* 从String中创建文件,如果此文件存在覆盖掉,如果不存在创建此文件。
*
* @param filePath
* @param fileData
* @return 写文件是否成功.
* @throws IOException
*/
public static boolean writeFile(String filePath, String fileData,
String charsetName) {
if (filePath == null || fileData == null) {
logger.debug("the fileName or fileData is null: fileName="
+ filePath + " fileData=" + fileData);
return false;
} else if (filePath.equals("") || filePath.trim().equals("")) {
logger.debug("the fileName or fileData is : fileName=" + filePath
+ " fileData=" + fileData);
return false;
}
FileOutputStream fileOutputStream = null;
try {
byte[] data = fileData.getBytes(charsetName);
File file = new File(filePath);
if (!file.exists()) {
logger.debug("this file is not exist!:" + filePath);
file.createNewFile();
logger.debug("creat file!:" + filePath);
}
fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(data);
fileOutputStream.close();
logger.debug("write file:" + filePath);
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
logger.debug(e.toString());
e.printStackTrace();
}
}
}
return false;
}
/**
* 将byte[]的数据写入文件,如果此文件存在覆盖掉,如果不存在创建此文件。
*
* @param filePath
* 文件全路径.
* @param fileData
* 文件数据.
* @return 写文件是否成功.
*/
public static boolean writeFile(String filePath, byte[] fileData) {
if (filePath == null || fileData == null) {
logger.debug("filePath or fileData is null");
return false;
} else if (filePath.trim().equals("")) {
logger.debug("filePath is \"\"!");
return false;
}
FileOutputStream write;
try {
write = new FileOutputStream(filePath);
write.write(fileData);
write.close();
logger.debug("write file:" + filePath + " success!");
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
}
return false;
}
/**
* 从String中创建文件,如果此文件存在覆盖掉,如果不存在创建此文件,如果文件路径上的目录没有则创建此目录。
*
* @param filePath
* @param fileData
* @return 写文件是否成功.
* @throws IOException
*/
public static boolean directWriteFile(String filePath, String fileData,
String charsetName) {
if (filePath == null || fileData == null) {
logger.debug("the fileName or fileData is null: fileName="
+ filePath + " fileData=" + fileData);
return false;
} else if (filePath.equals("") || filePath.trim().equals("")) {
logger.debug("the fileName or fileData is : fileName=" + filePath
+ " fileData=" + fileData);
return false;
}
String fileDir = filePath.substring(0, filePath.lastIndexOf(System
.getProperty("file.separator")));
boolean flag = makeDirectory(fileDir);
if (!flag) {
return false;
}
FileOutputStream fileOutputStream = null;
try {
byte[] data = fileData.getBytes(charsetName);
File file = new File(filePath);
if (!file.exists()) {
logger.debug("this file is not exist!:" + filePath);
file.createNewFile();
logger.debug("creat file!:" + filePath);
}
fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(data);
fileOutputStream.close();
logger.debug("write file:" + filePath);
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
logger.debug(e.toString());
e.printStackTrace();
}
}
}
return false;
}
/**
* 将byte[]的数据写入文件,如果此文件存在则覆盖掉,如果不存在创建此文件,目录不存在也直接创建其目录。
*
* @param filePath
* 文件全路径.
* @param fileData
* 文件数据.
* @return 写文件是否成功.
*/
public static boolean directWriteFile(String filePath, byte[] fileData) {
if (filePath == null || fileData == null) {
logger.debug("filePath or fileData is null");
return false;
} else if (filePath.trim().equals("")) {
logger.debug("filePath is \"\"!");
return false;
}
String fileDir = filePath.substring(0, filePath.lastIndexOf(System
.getProperty("file.separator")));
boolean flag = makeDirectory(fileDir);
if (!flag) {
return false;
}
FileOutputStream write;
try {
write = new FileOutputStream(filePath);
write.write(fileData);
write.close();
logger.debug("write file:" + filePath + " success!");
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
}
return false;
}
/**
* 将指定的文件解压缩到指定的文件夹,解压后的文件夹目录和给定的压缩文件名相同.
*
* @param zipFilePath
* 全路径
* @param unZipDirectory
* 全路径
* @return 解压缩文件是否成功.
* @throws IOException
*/
public static boolean unZipFile(String zipFilePath, String unZipDirectory)
throws IOException {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<?> entries = zipFile.entries();
if (zipFile == null) {
return false;
}
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
File f = new File(unZipDirectory + FILE_SEPARATOR
+ zipEntry.getName());
if (zipEntry.isDirectory()) {
if (!f.exists() && !f.mkdirs())
throw new IOException("Couldn't create directory: " + f);
} else {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(zipFile
.getInputStream(zipEntry));
File destDir = f.getParentFile();
if (!destDir.exists() && !destDir.mkdirs()) {
throw new IOException("Couldn't create dir " + destDir);
}
os = new BufferedOutputStream(new FileOutputStream(f));
int b = -1;
while ((b = is.read()) != -1) {
os.write(b);
}
} finally {
if (is != null)
is.close();
if (os != null)
os.close();
}
}
}
zipFile.close();
return true;
}
/**
* 将指定的文件解压缩到指定的文件夹,解压后的文件夹目录和给定的压缩文件名相同.
*
* @param zipFilePath
* 全路径
* @param unZipDirectory
* 全路径
* @return 解压缩文件是否成功.
* @throws IOException
*/
public static boolean unZipFile1(String zipFilePath, String unZipDirectory)
throws IOException {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<?> entries = zipFile.entries();
if (zipFile == null) {
return false;
}
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
File f = new File(unZipDirectory + FILE_SEPARATOR
+ ((String)zipEntry.getName()).substring(((String)zipEntry.getName()).indexOf("/")+1));
if (zipEntry.isDirectory()) {
if (!f.exists() && !f.mkdirs())
throw new IOException("Couldn't create directory: " + f);
} else {
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
is = new BufferedInputStream(zipFile
.getInputStream(zipEntry));
File destDir = f.getParentFile();
if (!destDir.exists() && !destDir.mkdirs()) {
throw new IOException("Couldn't create dir " + destDir);
}
os = new BufferedOutputStream(new FileOutputStream(f));
int b = -1;
while ((b = is.read()) != -1) {
os.write(b);
}
} finally {
if (is != null)
is.close();
if (os != null)
os.close();
}
}
}
zipFile.close();
return true;
}
/**
* 将给定的文件cut到指定的全路径,如果该路径不存在自动创建该路径。
*
* @param filePath
* 全路径。
* @param toDirectory
* 全路径。
* @return 是否成功 成功==true.
*/
public static boolean cutFile(String filePath, String toDirectory) {
if (filePath == null || toDirectory == null) {
logger
.info("the filePath or toDirectory is null ! when cut this file: "
+ filePath + "---- to:" + toDirectory);
return false;
} else if (filePath.trim().equals("") || toDirectory.trim().equals("")) {
logger
.info("the filePath or toDirectory is \"\"! when cut this file: "
+ filePath + "---- to:" + toDirectory);
return false;
}
if (copyFile(filePath, toDirectory)) {
int delte = deleteFile(filePath);
if (delte == 1) {
return true;
} else {
logger
.info("copy the file sucess form "
+ filePath
+ "----to:"
+ toDirectory
+ " but delete this file <<<<<<<faile>>>>>>> when cut this file.");
return false;
}
} else {
logger.debug("copy the file <<<<<<<faile>>>>>>> form " + filePath
+ "----to:" + toDirectory + " when cut this file.");
return false;
}
}
/**
* 将指定的文件夹cut到指定的路径下,如果该路径不存在,将窜关键该路径。
*
* @param directory
* 全路径
* @param toDirectory
* 全路径
* @return 是否成功 成功==true.
*/
public static boolean cutDirectory(String directory, String toDirectory) {
if (copyDirectory(directory, toDirectory)) {
boolean isDelete = deleteDirectory(directory);
if (isDelete) {
logger.debug("cut directory success: form"
+ " directory ---- to " + toDirectory);
return true;
} else {
logger
.info("copy directory sucess but delete <<<<<<<faile>>>>>>> when cut the directory form"
+ " directory ---- to " + toDirectory);
return false;
}
} else {
return false;
}
}
/**
* 判断是文件系统中是否存在此文件。
*
* @param filePath
* 全路径
* @return 文件在系统中=true.
*/
public static boolean isHave(String filePath) {
if (filePath == null) {
logger
.info("not know file isHave .filePath is null! at _File.isHave");
return true;
} else if (filePath.trim().equals("")) {
logger
.info("not know file isHave . filePath is \"\"! at _File.isHave");
return true;
}
File file = new File(filePath);
if (file.exists()) {
return true;
}
return false;
}
/**
* 将指定的文件copy到指定的路径下,如果该路径不存在将创建此路径。
*
* @param filePath
* 全路径
* @param toDirectoryPath
* 全路径
* @return 是否成功 成功==true.
*/
public static boolean copyFile(String filePath, String toDirectoryPath) {
if (filePath == null || toDirectoryPath == null) {
logger
.info("the filePath or toDirectory is null at _File.copyFile()");
return false;
} else if (filePath.trim().equals("")
|| toDirectoryPath.trim().equals("")) {
logger
.info("the filePath or toDirectory is \"\" at _File.copuFile()");
return false;
}
File directory = new File(toDirectoryPath);
if (!directory.exists()) {
makeDirectory(toDirectoryPath);
}
File file = new File(filePath);
String toFilePath = toDirectoryPath + FILE_SEPARATOR + file.getName();
File toFile = new File(toFilePath);
try {
if (!file.isFile()) {
logger.debug("can not get FileInputStream from this file:"
+ filePath);
return false;
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(toFile);
byte[] data = new byte[fis.available()];
int bytesRead;
while ((bytesRead = fis.read(data)) != -1) {
fos.write(data, 0, bytesRead);
}
fos.flush();
fos.close();
fis.close();
logger
.info("copy file file:" + file + "-----to:"
+ toDirectoryPath);
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
}
return false;
}
/**
* 将指定的文件copy到指定的路径下,如果该路径不存在将创建此路径。
*
* @param sfilePath
* 全路径
* @param toDirectoryPath
* 全路径
* @return 是否成功 成功==true.
*/
public static boolean copyFileByFilePath(String sfilePath, String dfilePath) {
if (sfilePath == null || dfilePath == null) {
logger.info("the filePath is null at _File.copyFile()");
return false;
} else if (sfilePath.trim().equals("") || dfilePath.trim().equals("")) {
logger.info("the filePath is \"\" at _File.copuFile()");
return false;
}
String toFileDir = dfilePath.substring(0, dfilePath.lastIndexOf(System
.getProperty("file.separator")));
boolean flag = makeDirectory(toFileDir);
if (!flag) {
return false;
}
File file = new File(sfilePath);
File toFile = new File(dfilePath);
try {
if (!file.isFile()) {
logger.debug("can not get FileInputStream from this file:"
+ sfilePath);
return false;
}
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(toFile);
byte[] data = new byte[fis.available()];
int bytesRead;
while ((bytesRead = fis.read(data)) != -1) {
fos.write(data, 0, bytesRead);
}
fos.flush();
fos.close();
fis.close();
logger.info("copy file file:" + file + "-----to:" + dfilePath);
return true;
} catch (FileNotFoundException e) {
logger.debug(e.getMessage());
} catch (IOException e) {
logger.debug(e.getMessage());
}
return false;
}
/**
* 将指定的文件夹copy到指定的路径下,如果指定的制定的路径不存在,创建此路径;指定的路径存在将覆盖.
*
* @param directoryPath
* 全路径
* @param toDirectoryPath
* 全路径
* @return 是否成功 成功==true.
*/
public static boolean copyDirectory(String directoryPath,
String toDirectoryPath) {
File file;
File[] files;
file = new File(directoryPath);
if (file.exists() && file.isDirectory()) {
files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].exists()) {
if (files[i].isDirectory()) {
copyDirectory(files[i].getPath(), toDirectoryPath
+ FILE_SEPARATOR + files[i].getName());
} else if (files[i].isFile()) {
copyFile(files[i].getPath(), toDirectoryPath);
}
}
}
}
} else {
logger.debug("file not exists or is not directory!");
return false;
}
logger.debug("copy directory form:" + directoryPath + "to :"
+ toDirectoryPath + ".");
return true;
}
/**
* 从给定的字符串中创建文件系统路径。
*
* @param directory
* 给定的路径表示字符串。
* @return 是否成功 成功==true.
*/
public static boolean makeDirectory(String directory) {
File file = new File(directory);
if (!file.exists()) {
if (file.mkdirs()) {
logger.debug("make dirctory success!:" + directory);
return true;
} else {
logger.debug("make dirctory <<<<<<<faile>>>>>>>!:" + directory);
return false;
}
} else {
logger.debug("this directory is existed!:" + directory);
return true;
}
}
/**
* 从文件中读出数据放到String中.
*
* @param filePath
* 文件路径.
* @param encoding
* 编码格式.
* @return 文件的String.
*/
public static String readFile(String filePath, String encoding) {
String contents = null;
FileInputStream fissrc = null;
try {
fissrc = new FileInputStream(filePath);
int len = fissrc.available();
byte[] data = new byte[len];
int actual = 0;
int bytesread = 0;
while ((bytesread != len) && (actual != -1)) {
actual = fissrc.read(data, bytesread, len - bytesread);
bytesread += actual;
}
contents = new String(data, encoding);
fissrc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fissrc != null){
try {
fissrc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return contents;
}
/**
* 获得所有的文件名.
*
* @param directoryPath
* @return
*/
@SuppressWarnings("unchecked")
public static List getAllFiles(String directoryPath) {
List allFiles = new ArrayList();
if (!isHave(directoryPath)) {
return allFiles;
} else {
File file = new File(directoryPath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
allFiles.add(files[i].getName());
}
return allFiles;
} else {
return allFiles;
}
}
}
/**
* 不区别文件和文件夹地获取其大小.
*
* @param path
* 文件或者文件夹的大小.
* @return long 类型的大小 bytes
* @throws FileNotFoundException
* @since 2006.4.22
*/
public static long getSize(String path) throws FileNotFoundException {
File file = new File(path);
if (file.isFile()) {
return getFileSize(path);
} else {
return getDirectorySize(path, 0);
}
}
/**
* 返回一个文件的大小.
*
* @param filePath
* 文件的全路径.
* @return long bytes value 文件大小.
* @throws FileNotFoundException
* @since 2006.4.22
*/
public static long getFileSize(String filePath)
throws FileNotFoundException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException("this file is not exited: "
+ filePath);
}
return file.length();
}
/**
* 返回一个文件夹的大小.
*
* @param directoryPath
* 文件夹的全路径.
* @return 文件夹大小.
* @throws FileNotFoundException
* @since 2006.4.22
*/
public static long getDirectorySize(String directoryPath)
throws FileNotFoundException {
return getDirectorySize(directoryPath, 0);
}
/**
* 递归的获取文件夹的每一个文件的大小,并计算总的大小.
*
* @param directoryPath
* 文件夹大小.
* @param size
* 递归参数
* @return long bytes value;
* @throws FileNotFoundException
* @since 2006.4.22
*/
private static long getDirectorySize(String directoryPath, long size)
throws FileNotFoundException {
File file = new File(directoryPath);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
String filePath = files[i].getAbsolutePath();
if (files[i].isDirectory()) {
size = getDirectorySize(filePath, size);
} else {
size += getFileSize(filePath);
}
}
return size;
}
/**
* @author xiaobao
* @param filePath
* @return long bytes value;
* @since 1.0.0 从文件中读出数据放到byte中.
* @createTime 2006-11-06 13:50:20
*/
public static byte[] readFileByByte(String filePath) {
byte[] data = null;
FileInputStream fissrc;
try {
fissrc = new FileInputStream(filePath);
int len = fissrc.available();
data = new byte[len];
int actual = 0;
int bytesread = 0;
while ((bytesread != len) && (actual != -1)) {
actual = fissrc.read(data, bytesread, len - bytesread);
bytesread += actual;
}
fissrc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
/**
* 删除非空目录
*
* @param dir
* @throws IOException
* @author lixiang
* @create 2008-8-30 下午12:46:18
* @since
*/
public static void deleteDirectory(File dir) throws IOException {
if ((dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " + dir
+ " is not a directory. ");
}
File[] entries = dir.listFiles();
int sz = entries.length;
for (int i = 0; i < sz; i++) {
if (entries[i].isDirectory()) {
deleteDirectory(entries[i]);
} else {
entries[i].delete();
}
}
dir.delete();
}
/**
* 捕捉屏幕
*
* @param fileName
* @param top
* @param left
* @create 2008-8-30 下午08:03:10
* @since
*/
public static void snapShotsf(String fileName, int left, int top) {
try {
BufferedImage screenshot = (new Robot())
.createScreenCapture(new Rectangle(left, top, 640, 526));
String name = fileName + ".jpg";
File f = new File(name);
ImageIO.write(screenshot, "jpg", f);
} catch (Exception ex) {
System.out.println(ex);
}
}
/**
* I帧转图片
*
* @param mpgFilePath
* MPG的文件路径 如:d:/test/s22.MPG
* @param targetFilePath
* 生成的jpg文件路径,存放文件的文件夹必须存在 如:d:/abc/t22.jpg,d:/abc必须存在
* @param processerFolder
* 文件夹,里面有处理文件转换用到的dll 文件,exe文件 如:d:/abc/mpg2jpg (在windows下会用到)
* @return
*/
public static boolean processJPG(String mpgFilePath, String targetFilePath,
String processerFolder, int height, int width) {
String osName = System.getProperty("os.name");
logger.debug("current os.name: " + osName);
if (osName.indexOf("Windows") >= 0) {
mpgFilePath = reverse(mpgFilePath, false);
targetFilePath = reverse(targetFilePath, false);
processerFolder = reverse(processerFolder, false);
FileWriter fw = null;
String directory = processerFolder.substring(0, 1);
try {
fw = new FileWriter(processerFolder + "/process.bat");
fw.write("@echo off\r\n");
fw.write(directory + ":\r\n");
fw.write("cd\\"
+ processerFolder.substring(processerFolder
.indexOf(":/") + 2) + "\r\n");
fw.write("ffmpeg -i " + "mpg"
+ mpgFilePath.substring(mpgFilePath.lastIndexOf("/"))
+ " -y -f image2 -t 0.001 -s " + width + "x" + height
+ " " + targetFilePath + "\r\n");
fw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 拷贝s22.MPG到 processerFolder 的mpg下
String sfilePath = mpgFilePath;
String dfilePath = processerFolder + "/mpg"
+ mpgFilePath.substring(mpgFilePath.lastIndexOf("/"));
dfilePath = reverse(dfilePath, true);
deleteFile(dfilePath);
copyFileByFilePath(sfilePath, dfilePath);
String cmd = "cmd.exe /c " + directory + ":/"
+ processerFolder.substring(2) + "/process.bat";
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
processJPGLinux(mpgFilePath, targetFilePath, processerFolder,
height, width);
}
logger.debug("conver MPG to JPG sucess: " + targetFilePath);
return true;
}
/**
* I帧转图片
*
* @param mpgFilePath
* MPG的文件路径 如:d:/test/s22.MPG
* @param targetFilePath
* 生成的jpg文件路径,存放文件的文件夹必须存在 如:d:/abc/t22.jpg,d:/abc必须存在
* @param processerFolder
* 处理文件转换用到的dll 文件,exe文件
* @return
*/
private static void processJPGLinux(String mpgFilePath,
String targetFilePath, String processerFolder, int height, int width) {
int p = targetFilePath.split("/")[(targetFilePath.split("/").length) - 1]
.length();
int g = targetFilePath.length();
String ggg = targetFilePath.substring(0, g - p - 1);
FileWriter fw = null;
try {
fw = new FileWriter(ggg + "/www.sh");
fw.write("#!/bin/bash\n");
fw.write("cd " + processerFolder + "\n");
fw.write("ffmpeg -i " + mpgFilePath + " -y -f image2 -t 0.001 -s "
+ width + "x" + height + " " + targetFilePath);
fw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
String cmd = "/bin/sh " + ggg + "/www.sh";
try {
Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 斜杠替换
*
* @param sourceStr
* @param lineType
* true : 全转换为"\"; false 全转换为"/"
* @return
*/
private static String reverse(String sourceStr, boolean lineType) {
if (lineType) {
Pattern pattern = Pattern.compile("/", Pattern.DOTALL);
Matcher matcher = pattern.matcher(sourceStr);
sourceStr = matcher.replaceAll("\\\\"); // ת�����
} else {
Pattern pattern = Pattern.compile("\\\\", Pattern.DOTALL);
Matcher matcher = pattern.matcher(sourceStr);
sourceStr = matcher.replaceAll("/"); // ת�����
}
return sourceStr;
}
/**
* @param filePath
* String 文件路径
* @return byte[]
* @since 从指定的文件中读出信息,返回byte[]。
*/
public static byte[] readFileByte(String filePath) {
byte[] data = null;
FileInputStream fissrc;
try {
fissrc = new FileInputStream(filePath);
int len = fissrc.available();
data = new byte[len];
int actual = 0;
int bytesread = 0;
while ((bytesread != len) && (actual != -1)) {
actual = fissrc.read(data, bytesread, len - bytesread);
bytesread += actual;
}
fissrc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
public byte[] doDownload(String fileName)
{
FileInputStream fis;
byte[] data =null;
FileChannel fc;
try {
fis = new FileInputStream(System.getProperty("java.io.tmpdir") + "/" + fileName);
fc = fis.getChannel();
data = new byte[(int)(fc.size())];
ByteBuffer bb = ByteBuffer.wrap(data);
fc.read(bb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
/**
* 判断文件后缀名是否为zip,rar
*/
public static boolean judgeFileZip(String fileName) {
String[] zip = { "zip", "ziP", "zIp", "zIP", "Zip", "ZiP", "ZIp", "ZIP" };
String type = fileName.substring(fileName.lastIndexOf(".")+1, fileName
.length());
if(fileName.indexOf(".")==-1)return false;
boolean b = false;
for (int i = 0; i < zip.length; i++) {
if (type.equals(zip[i])) {
b = true;
break;
}
}
return b;
}
public static void main(String[] args) {
// FileFiend.deleteFile("E:/tomcat-5.5.27/webapps/PortalBackOffice/zipfile/qw.zip");
// FileFiend.deleteDirectory("E:/tomcat-5.5.27/webapps/PortalBackOffice/zipfile/xxxxx_1.0");
String portalname = "xxxxxxx_1.0";
String[] st = portalname.split("\\.");
int j = Integer.parseInt(st[1]);
logger.info(j);
logger.info(st[0]);
}
}
|
FileCopyUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import cn.cd.sg.validate.utils.Validate;
public abstract class FileCopyUtils {
public static final int BUFFER_SIZE = 4096;
public static int copy(File in, File out) throws IOException {
Validate.notNull(in, "No input File specified");
Validate.notNull(out, "No output File specified");
return copy(new BufferedInputStream(new FileInputStream(in)),
new BufferedOutputStream(new FileOutputStream(out)));
}
public static void copy(byte[] in, File out) throws IOException {
Validate.notNull(in, "No input byte array specified");
Validate.notNull(out, "No output File specified");
ByteArrayInputStream inStream = new ByteArrayInputStream(in);
OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
copy(inStream, outStream);
}
public static byte[] copyToByteArray(File in) throws IOException {
Validate.notNull(in, "No input File specified");
return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
}
public static int copy(InputStream in, OutputStream out) throws IOException {
Validate.notNull(in, "No InputStream specified");
Validate.notNull(out, "No OutputStream specified");
try {
int byteCount = 0;
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
}
finally {
try {
in.close();
}
catch (IOException ex) {
}
try {
out.close();
}
catch (IOException ex) {
}
}
}
public static void copy(byte[] in, OutputStream out) throws IOException {
Validate.notNull(in, "No input byte array specified");
Validate.notNull(out, "No OutputStream specified");
try {
out.write(in);
}
finally {
try {
out.close();
}
catch (IOException ex) {
}
}
}
public static byte[] copyToByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
copy(in, out);
return out.toByteArray();
}
public static int copy(Reader in, Writer out) throws IOException {
Validate.notNull(in, "No Reader specified");
Validate.notNull(out, "No Writer specified");
try {
int byteCount = 0;
char[] buffer = new char[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
return byteCount;
}
finally {
try {
in.close();
}
catch (IOException ex) {
}
try {
out.close();
}
catch (IOException ex) {
}
}
}
public static void copy(String in, Writer out) throws IOException {
Validate.notNull(in, "No input String specified");
Validate.notNull(out, "No Writer specified");
try {
out.write(in);
}
finally {
try {
out.close();
}
catch (IOException ex) {
}
}
}
public static String copyToString(Reader in) throws IOException {
StringWriter out = new StringWriter();
copy(in, out);
return out.toString();
}
}
|
DeleteFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
public class DeleteFileUtils {
/**
* 删除文件,可以是单个文件或文件夹
* @param fileName 待删除的文件名
* @return 文件删除成功返回true,否则返回false
*/
public static boolean delete(String fileName){
File file = new File(fileName);
if (!file.exists()){
System.out.println("删除文件失败:" + fileName + "文件不存在!");
return false;
} else {
if (file.isFile()){
return DeleteFileUtils.deleteFile(fileName);
} else {
return DeleteFileUtils.deleteDirectory(fileName);
}
}
}
/**
* 删除单个文件
* @param fileName 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName){
File file = new File(fileName);
//如果文件路径对应的文件存在,并且是一个文件,则直接删除。
if (file.exists() && file.isFile()){
if(file.delete()){
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
}else{
System.out.println("删除单个文件失败:" + fileName + "文件不存在!");
return false;
}
}
/**
* 删除目录(文件夹)以及目录下的文件,只删除文件夹
* @param dir 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String dir){
//如果dir不以文件分隔符结尾,自动添加文件分隔符。
if (!dir.endsWith(File.separator)){
dir = dir + File.separator;
}
File dirFile = new File(dir);
//如果dir对应的文件不存在,或者不是一个文件夹,则退出
if (!dirFile.exists() || (!dirFile.isDirectory())){
System.out.println("删除目录失败:" + dir + "目录不存在!");
return false;
}
boolean flag = true;
//删除文件夹下所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
//删除子文件
if (files[i].isFile()){
flag = DeleteFileUtils.deleteFile(files[i].getAbsolutePath());
if (!flag){
break;
}
}
//删除子目录
else if (files[i].isDirectory()){
flag = DeleteFileUtils.deleteDirectory(files[i].getAbsolutePath());
if (!flag){
break;
}
}
}
if (!flag){
System.out.println("删除目录失败!");
return false;
}
//删除当前目录
if (dirFile.delete()){
System.out.println("删除目录" + dir + "成功!");
return true;
} else {
return false;
}
}
public static void main(String[] args) {
//删除单个文件
String file = "C:/temp/temp0/temp1/temp.txt";
DeleteFileUtils.deleteFile(file);
System.out.println();
//删除一个目录
String dir = "C:/temp/temp0/temp1";
DeleteFileUtils.deleteDirectory(dir);
System.out.println();
//删除文件
dir = "C:/temp/temp0";
DeleteFileUtils.delete(dir);
}
}
|
CreateFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
import java.io.IOException;
public class CreateFileUtils {
/**
* 创建单个文件
* @param destFileName 目标文件名
* @return 创建成功,返回true,否则返回false
*/
public static boolean createFile(String destFileName) {
File file = new File(destFileName);
if (file.exists()) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
// 判断目标文件所在的目录是否存在
if (!file.getParentFile().exists()) {
// 如果目标文件所在的文件夹不存在,则创建父文件夹
System.out.println("目标文件所在目录不存在,准备创建它!");
if (!file.getParentFile().mkdirs()) {
System.out.println("创建目标文件所在的目录失败!");
return false;
}
}
// 创建目标文件
try {
if (file.createNewFile()) {
System.out.println("创建单个文件" + destFileName + "成功!");
return true;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out
.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
/**
* 创建目录
* @param destDirName 目标目录名
* @return 目录创建成功放回true,否则返回false
*/
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 创建目标目录
if (dir.mkdirs()) {
System.out.println("创建目录" + destDirName + "成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}
/**
* 创建临时文件
* @param prefix 临时文件名的前缀
* @param suffix 临时文件名的后缀
* @param dirName 临时文件所在的目录,如果输入null,则在用户的文档目录下创建临时文件
* @return 临时文件创建成功返回true,否则返回false
*/
public static String createTempFile(String prefix, String suffix,
String dirName) {
File tempFile = null;
if (dirName == null) {
try {
// 在默认文件夹下创建临时文件
tempFile = File.createTempFile(prefix, suffix);
// 返回临时文件的路径
return tempFile.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
}
} else {
File dir = new File(dirName);
// 如果临时文件所在目录不存在,首先创建
if (!dir.exists()) {
if (CreateFileUtils.createDir(dirName)) {
System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
return null;
}
}
try {
// 在指定目录下创建临时文件
tempFile = File.createTempFile(prefix, suffix, dir);
return tempFile.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
}
}
}
public static void main(String[] args) {
// 创建目录
String dirName = "C:/temp/temp0/temp1";
CreateFileUtils.createDir(dirName);
// 创建文件
String fileName = dirName + "/temp2/tempFile.txt";
CreateFileUtils.createFile(fileName);
// 创建临时文件
String prefix = "temp";
String surfix = ".txt";
for (int i = 0; i < 10; i++) {
System.out.println("创建了临时文件: "
+ CreateFileUtils.createTempFile(prefix, surfix, dirName));
}
}
}
|
CopyFileUtils |
java |
|
package cn.cd.sg.file.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFileUtils {
/**
* 复制单个文件, 如果目标文件存在,则不覆盖。
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String destFileName){
return CopyFileUtils.copyFile(srcFileName, destFileName, false);
}
/**
* 复制单个文件
* @param srcFileName 待复制的文件名
* @param destFileName 目标文件名
* @param overlay 如果目标文件存在,是否覆盖
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName,
String destFileName, boolean overlay) {
//判断原文件是否存在
File srcFile = new File(srcFileName);
if (!srcFile.exists()){
System.out.println("复制文件失败:原文件" + srcFileName + "不存在!");
return false;
} else if (!srcFile.isFile()){
System.out.println("复制文件失败:" + srcFileName + "不是一个文件!");
return false;
}
//判断目标文件是否存在
File destFile = new File(destFileName);
if (destFile.exists()){
//如果目标文件存在,而且复制时允许覆盖。
if (overlay){
//删除已存在的目标文件,无论目标文件是目录还是单个文件
System.out.println("目标文件已存在,准备删除它!");
if(!DeleteFileUtils.delete(destFileName)){
System.out.println("复制文件失败:删除目标文件" + destFileName + "失败!");
return false;
}
} else {
System.out.println("复制文件失败:目标文件" + destFileName + "已存在!");
return false;
}
} else {
if (!destFile.getParentFile().exists()){
//如果目标文件所在的目录不存在,则创建目录
System.out.println("目标文件所在的目录不存在,准备创建它!");
if(!destFile.getParentFile().mkdirs()){
System.out.println("复制文件失败:创建目标文件所在的目录失败!" );
return false;
}
}
}
//准备复制文件
int byteread = 0;//读取的位数
InputStream in = null;
OutputStream out = null;
try {
//打开原文件
in = new FileInputStream(srcFile);
//打开连接到目标文件的输出流
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
//一次读取1024个字节,当byteread为-1时表示文件已经读完
while ((byteread = in.read(buffer)) != -1) {
//将读取的字节写入输出流
out.write(buffer, 0, byteread);
}
System.out.println("复制单个文件" + srcFileName + "至" + destFileName + "成功!");
return true;
} catch (Exception e) {
System.out.println("复制文件失败:" + e.getMessage());
return false;
} finally {
//关闭输入输出流,注意先关闭输出流,再关闭输入流
if (out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 复制整个目录的内容,如果目标目录存在,则不覆盖
* @param srcDirName 待复制的目录名
* @param destDirName 目标目录名
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName){
return CopyFileUtils.copyDirectory(srcDirName, destDirName, false);
}
/**
* 复制整个目录的内容
* @param srcDirName 待复制的目录名
* @param destDirName 目标目录名
* @param overlay 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String destDirName,
boolean overlay) {
// 判断原目录是否存在
File srcDir = new File(srcDirName);
if (!srcDir.exists()) {
System.out.println("复制目录失败:原目录" + srcDirName + "不存在!");
return false;
} else if (!srcDir.isDirectory()) {
System.out.println("复制目录失败:" + srcDirName + "不是一个目录!");
return false;
}
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
File destDir = new File(destDirName);
// 如果目标文件夹存在,
if (destDir.exists()) {
if (overlay) {
// 允许覆盖则删除已存在的目标目录
System.out.println("目标目录已存在,准备删除它!");
if (!DeleteFileUtils.delete(destDirName)) {
System.out.println("复制目录失败:删除目标目录" + destDirName + "失败!");
}
} else {
System.out.println("复制目录失败:目标目录" + destDirName + "已存在!");
return false;
}
} else {
// 创建目标目录
System.out.println("目标目录不存在,准备创建它!");
if (!destDir.mkdirs()) {
System.out.println("复制目录失败:创建目标目录失败!");
return false;
}
}
boolean flag = true;
// 列出源文件夹下所有文件(包括子目录)的文件名
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) {
// 如果是一个单个文件,则进行复制
if (files[i].isFile()) {
flag = CopyFileUtils.copyFile(files[i].getAbsolutePath(),
destDirName + files[i].getName());
if (!flag){
break;
}
}
// 如果是子目录,继续复制目录
if (files[i].isDirectory()) {
flag = CopyFileUtils.copyDirectory(files[i].getAbsolutePath(),
destDirName + files[i].getName());
if (!flag){
break;
}
}
}
if (!flag){
System.out.println("复制目录" + srcDirName + "至" + destDirName+ "失败!");
return false;
}
System.out.println("复制目录" + srcDirName + "至" + destDirName+ "成功!");
return true;
}
public static void main(String[] args) {
//复制单个文件,如果目标存在,则覆盖
String srcPath = "C:/temp/tempfile0.txt";
String destPath = "C:/temp_bak/tempfile0_bak.txt";
CopyFileUtils.copyFile(srcPath, destPath, true);
//如果目标存在,则不覆盖
CopyFileUtils.copyFile(srcPath, destPath);
System.out.println();
//复制文件夹,如果目标存在,则覆盖
String srcDir = "C:/temp";
String destDir = "D:/temp";
CopyFileUtils.copyDirectory(srcDir, destDir, true);
}
}
|
DateUtils |
java |
|
package cn.cd.sg.date.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class DateUtils extends Date {
private static final long serialVersionUID = 1L;
public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
public DateUtils() {
super();
}
/**
* 描述 : (得到当前年)
* 方法名: getCurrYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:00:51
* @return
* @return :int
*/
public static int getCurrYear() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.YEAR);
}
/**
* 描述 : (得到当前月份 注意,这里的月份依然是从0开始的)
* 方法名: getCurrMonth
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:01:06
* @return
* @return :int
*/
public static int getCurrMonth() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.MONTH);
}
/**
* 描述 : (得到当前日)
* 方法名: getCurrDay
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:02:14
* @return
* @return :int
*/
public static int getCurrDay() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 描述 : (得到当前小时)
* 方法名: getCurrHour
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:03:27
* @return
* @return :int
*/
public static int getCurrHour() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.HOUR);
}
/**
* 描述 : (得到当前分钟)
* 方法名: getCurrMinute
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:07:23
* @return
* @return :int
*/
public static int getCurrMinute() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.MINUTE);
}
/**
* 描述 : (得到当前秒)
* 方法名: getCurrSecond
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:07:17
* @return
* @return :int
*/
public static int getCurrSecond() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.SECOND);
}
/**
* 描述 : (得到当前时间的毫秒数)
* 方法名: getCurrentTimeMillis
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:05:43
* @return
* @return :Long
*/
public static Long getCurrentTimeMillis() {
return System.currentTimeMillis();
}
/**
* 描述 : (得到当前星期)
* 方法名: getCurrWeek
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:06:06
* @return
* @return :int
*/
public static int getCurrWeek() {
Calendar cal = Calendar.getInstance();
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* 描述 : (获取日期对应的星期(中文))
* 方法名: getCurrWeekByCh
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:07:09
* @param date
* @return
* @return :String
*/
public static String getWeekByCurrTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 获取星期值(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY)
switch (cal.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY: {
return "星期天";
}
case Calendar.MONDAY: {
return "星期一";
}
case Calendar.TUESDAY: {
return "星期二";
}
case Calendar.WEDNESDAY: {
return "星期三";
}
case Calendar.THURSDAY: {
return "星期四";
}
case Calendar.FRIDAY: {
return "星期五";
}
case Calendar.SATURDAY: {
return "星期六";
}
}
return null;
}
/**
* 描述 : (Date类型转换到Calendar类型)
* 方法名: Date2Calendar
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:10:32
* @param date
* @return
* @return :Calendar
*/
public static Calendar Date2Calendar(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
/**
* 描述 : (Calendar类型转换到Date类型)
* 方法名: calendar2Date
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:10:40
* @param cal
* @return
* @return :Date
*/
public static Date calendar2Date(Calendar cal) {
return cal.getTime();
}
/**
* 描述 : (Date类型转换到Timestamp类型)
* 方法名: date2Timestamp
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:10:49
* @param date
* @return
* @return :Timestamp
*/
public static Timestamp date2Timestamp(Date date) {
return new Timestamp(date.getTime());
}
/**
* 描述 : (Calendar类型转换到Timestamp类型)
* 方法名: calendar2Timestamp
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:10:57
* @param cal
* @return
* @return :Timestamp
*/
public static Timestamp calendar2Timestamp(Calendar cal) {
return new Timestamp(cal.getTimeInMillis());
}
/**
* 描述 : (Timestamp类型转换到Calendar类型)
* 方法名: timestamp2Calendar
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:11:06
* @param timestamp
* @return
* @return :Calendar
*/
public static Calendar timestamp2Calendar(Timestamp timestamp) {
Calendar cal = Calendar.getInstance();
cal.setTime(timestamp);
return cal;
}
/**
* 描述 : (当前时间的下一天时间)
* 方法名: nextDate
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:11:15
* @return
* @return :Date
*/
public static Date nextDate() {
return nextDate(new DateUtils(), 1);
}
/**
* 描述 : (获取任意时间后num天的时间)
* 方法名: nextDate
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:12:15
* @param date
* @param num
* @return
* @return :Date
*/
public static Date nextDate(Date date, int num) {
Calendar cla = Calendar.getInstance();
cla.setTime(date);
cla.add(Calendar.DAY_OF_YEAR, num);
return cla.getTime();
}
/**
* 描述 : (获取任意时间后num天的时间)
* 方法名: nextDate
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:14:25
* @param date
* @param num
* @return
* @throws ParseException
* @return :Date
*/
public static Date nextDate(String date, int num) throws ParseException {
if (date == null){
return null;
}
SimpleDateFormat sdf = null;
if (date.indexOf("-") != -1){
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}else if (date.indexOf("-") != -1){
sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss");
}else if (date.indexOf("/") != -1){
sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}else if (date.indexOf("CST") != -1){
sdf = new SimpleDateFormat();
}else{
System.out.println("no match format:");
}
return nextDate(sdf.parse(date), num);
}
/**
* 描述 : 获取当天时间num天后的时间 如果num小于0则返回当前时间的前num天的时间
* 否则返回当天时间后num天的时间
* 方法名: nextDate
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:16:19
* @param num
* @return
* @return :Date
*/
public static Date nextDate(int num) {
return nextDate(new Date(), num);
}
/**
* 描述 : (取得当前日期是多少周)
* 方法名: getWeekOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:18:03
* @param date
* @return
* @return :int
*/
public static int getWeekOfYear(Date date) {
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
/**
* 设置一年中第一个星期所需的最少天数,
* 例如,如果定义第一个星期包含一年第一个月的第一天,则使用值 1 调用此方法。
* 如果最少天数必须是一整个星期,则使用值 7 调用此方法。
**/
c.setMinimalDaysInFirstWeek(1);
c.setTime(date);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
* 描述 : (得到某一年周的总数)
* 方法名: getMaxWeekNumOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:19:10
* @param year
* @return
* @return :int
*/
public static int getMaxWeekNumOfYear(int year) {
Calendar c = Calendar.getInstance();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
return getWeekOfYear(c.getTime());
}
/**
* 描述 : (得到某年某周的第一天)
* 方法名: getFirstDayOfWeek
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:21:22
* @param year
* @param week
* @return
* @return :Date
*/
public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.WEEK_OF_YEAR, week);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 设置周一
c.setFirstDayOfWeek(Calendar.MONDAY);
return c.getTime();
}
/**
* 描述 : (得到当周的第一天)
* 方法名: getFirstDayOfWeek
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:22:51
* @param date
* @return
* @return :Date
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 设置周一
c.setFirstDayOfWeek(Calendar.MONDAY);
return c.getTime();
}
/**
* 描述 : (得到某年某周的最后一天)
* 方法名: getLastDayOfWeek
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:24:56
* @param year
* @param week
* @return
* @return :Date
*/
public static Date getLastDayOfWeek(int year, int week) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.WEEK_OF_YEAR, week);
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
/**
* 描述 : (得到当前周的周的最后一天)
* 方法名: getLastDayOfWeek
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:26:05
* @param date
* @return
* @return :Date
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
/**
* 描述 : (得到某年某月的第一天)
* 方法名: getFirstDayOfMonth
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:26:41
* @param year
* @param month
* @return
* @return :Date
*/
public static Date getFirstDayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 描述 : (获得当前月的第一天)
* 方法名: getFirstDayOfMonth
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:28:08
* @param date
* @return
* @return :Date
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 描述 : (得到某年某月的最后一天)
* 方法名: getLastDayOfMonth
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:28:50
* @param year
* @param month
* @return
* @return :Date
*/
public static Date getLastDayOfMonth(int year, int month) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month - 1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 描述 : (获得当前月的最后一天)
* 方法名: getLastDayOfMonth
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:30:34
* @param date
* @return
* @return :Date
*/
public static Date getLastDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 描述 : (得到某年某季度第一天)
* 方法名: getFirstDayOfQuarter
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:30:46
* @param year
* @param quarter
* @return
* @return :Date
*/
public static Date getFirstDayOfQuarter(int year, int quarter) {
int month = 0;
if (quarter > 4) {
return null;
} else {
month = (quarter - 1) * 3 + 1;
}
return getFirstDayOfMonth(year, month);
}
/**
* 描述 : (得到某年某季度最后一天)
* 方法名: getLastDayOfQuarter
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:32:10
* @param year
* @param quarter
* @return
* @return :Date
*/
public static Date getLastDayOfQuarter(int year, int quarter) {
int month = 0;
if (quarter > 4) {
return null;
} else {
month = quarter * 3;
}
return getLastDayOfMonth(year, month);
}
/**
* 描述 : (得到某年第一天)
* 方法名: getFirstDayOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:33:18
* @param year
* @return
* @return :Date
*/
public static Date getFirstDayOfYear(int year) {
return getFirstDayOfQuarter(year, 1);
}
/**
* 描述 : (得到当年第一天)
* 方法名: getFirstDayOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:34:13
* @param date
* @return
* @return :Date
*/
public static Date getFirstDayOfYear(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
return getFirstDayOfYear(year);
}
/**
* 描述 : (得到某年最后一天)
* 方法名: getLastDayOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:34:51
* @param year
* @return
* @return :Date
*/
public static Date getLastDayOfYear(int year) {
return getLastDayOfQuarter(year, 4);
}
/**
* 描述 : (得到当年最后一天)
* 方法名: getLastDayOfYear
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:36:05
* @param date
* @return
* @return :Date
*/
public static Date getLastDayOfYear(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
return getLastDayOfYear(year);
}
/**
* 描述 : (获取本周的开始时间 示例:2013-05-13 00:00:00)
* 方法名: getWeekStart
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:36:23
* @return
* @return :Date
*/
public static Date getWeekStart() {// 当周开始时间
Calendar currentDate = Calendar.getInstance();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 0);
currentDate.set(Calendar.MINUTE, 0);
currentDate.set(Calendar.SECOND, 0);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return (Date) currentDate.getTime();
}
/**
* 描述 : (获取本周的结束时间 示例:2013-05-19 23:59:59)
* 方法名: getWeekEnd
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:37:12
* @return
* @return :Date
*/
public static Date getWeekEnd() {// 当周结束时间
Calendar currentDate = Calendar.getInstance();
currentDate.setFirstDayOfWeek(Calendar.MONDAY);
currentDate.set(Calendar.HOUR_OF_DAY, 23);
currentDate.set(Calendar.MINUTE, 59);
currentDate.set(Calendar.SECOND, 59);
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return (Date) currentDate.getTime();
}
/**
* 描述 : (得到指定或者当前时间前n天的Calendar)
* 方法名: getBeforeNDays
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:37:46
* @param n
* @return
* @return :Calendar
*/
public static Calendar getBeforeNDays(int n) {
Calendar cal = null;
// 偏移量,给定n天的毫秒数
long offset = n * 24 * 60 * 60 * 1000;
if (cal != null) {
cal.setTimeInMillis(cal.getTimeInMillis() - offset);
} else {
cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() - offset);
}
return cal;
}
/**
* 描述 : (得到指定或者当前时间后n天的Calendar)
* 方法名: getAfterNDays
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:37:58
* @param n
* @return
* @return :Calendar
*/
public static Calendar getAfterNDays(int n) {
Calendar cal = null;
// 偏移量,给定n天的毫秒数
long offset = n * 24 * 60 * 60 * 1000;
if (cal != null) {
cal.setTimeInMillis(cal.getTimeInMillis() + offset);
} else {
cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() + offset);
}
return cal;
}
/**
* 描述 : (获取当前时间的后一天)
* 方法名: getTomorrowDay
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:38:09
* @return
* @return :Calendar
*/
public static Calendar getTomorrowDay() {
long offset = 1 * 24 * 60 * 60 * 1000;
Calendar cal = null;
if (cal != null) {
cal.setTimeInMillis(cal.getTimeInMillis() + offset);
} else {
cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() + offset);
}
return cal;
}
/**
* 描述 : (获取当前时间的上一天)
* 方法名: getYesterDay
* 创建人:孙刚
* 创建时间:2014-2-8 下午05:39:41
* @return
* @return :Calendar
*/
public static Calendar getYesterDay() {
long offset = 1 * 24 * 60 * 60 * 1000;
Calendar cal = null;
if (cal != null) {
cal.setTimeInMillis(cal.getTimeInMillis() - offset);
} else {
cal = Calendar.getInstance();
cal.setTimeInMillis(cal.getTimeInMillis() - offset);
}
return cal;
}
}
|
DateFormatUtils |
java |
|
package cn.cd.sg.date.utils;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;
/**
* 描述:
* 项目名称:utils
* 类名称:DateFormatUtils
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:42:21
* 修改人1:xxx
* 修改时间1:xxxx-xx-xx
* 修改备注:
* @version 1.0
*/
public class DateFormatUtils {
public static final FastDateFormat ISO_DATETIME_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
public static final FastDateFormat ISO_DATETIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ");
public static final FastDateFormat ISO_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");
public static final FastDateFormat ISO_DATE_TIME_ZONE_FORMAT = FastDateFormat.getInstance("yyyy-MM-ddZZ");
public static final FastDateFormat ISO_TIME_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ss");
public static final FastDateFormat ISO_TIME_TIME_ZONE_FORMAT = FastDateFormat.getInstance("'T'HH:mm:ssZZ");
public static final FastDateFormat ISO_TIME_NO_T_FORMAT = FastDateFormat.getInstance("HH:mm:ss");
public static final FastDateFormat ISO_TIME_NO_T_TIME_ZONE_FORMAT = FastDateFormat.getInstance("HH:mm:ssZZ");
public static final FastDateFormat SMTP_DATETIME_FORMAT;
static {
SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
}
/**
* @Description:构造函数
* @throws
*/
public DateFormatUtils() {}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: formatUTC
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:43:42
* @param millis
* @param pattern
* @return :String
*/
public static String formatUTC(long millis, String pattern){
return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: formatUTC
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:46:10
* @param date
* @param pattern
* @return
* @return :String
*/
public static String formatUTC(Date date, String pattern){
return format(date, pattern, DateUtils.UTC_TIME_ZONE, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: formatUTC
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:46:42
* @param millis
* @param pattern
* @param locale
* @return :String
*/
public static String formatUTC(long millis, String pattern, Locale locale){
return format(new Date(millis), pattern, DateUtils.UTC_TIME_ZONE, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: formatUTC
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:47:11
* @param date
* @param pattern
* @param locale
* @return
* @return :String
*/
public static String formatUTC(Date date, String pattern, Locale locale){
return format(date, pattern, DateUtils.UTC_TIME_ZONE, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:47:38
* @param millis
* @param pattern
* @return
* @return :String
*/
public static String format(long millis, String pattern){
return format(new Date(millis), pattern, null, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:48:00
* @param date
* @param pattern
* @return
* @return :String
*/
public static String format(Date date, String pattern){
return format(date, pattern, null, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:48:23
* @param calendar
* @param pattern
* @return
* @return :String
*/
public static String format(Calendar calendar, String pattern){
return format(calendar, pattern, null, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:48:50
* @param millis
* @param pattern
* @param timeZone
* @return
* @return :String
*/
public static String format(long millis, String pattern, TimeZone timeZone){
return format(new Date(millis), pattern, timeZone, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:49:46
* @param date
* @param pattern
* @param timeZone
* @return
* @return :String
*/
public static String format(Date date, String pattern, TimeZone timeZone){
return format(date, pattern, timeZone, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:50:11
* @param calendar
* @param pattern
* @param timeZone
* @return
* @return :String
*/
public static String format(Calendar calendar, String pattern, TimeZone timeZone){
return format(calendar, pattern, timeZone, null);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:50:36
* @param millis
* @param pattern
* @param locale
* @return
* @return :String
*/
public static String format(long millis, String pattern, Locale locale){
return format(new Date(millis), pattern, null, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:51:01
* @param date
* @param pattern
* @param locale
* @return
* @return :String
*/
public static String format(Date date, String pattern, Locale locale){
return format(date, pattern, null, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:51:31
* @param calendar
* @param pattern
* @param locale
* @return
* @return :String
*/
public static String format(Calendar calendar, String pattern, Locale locale){
return format(calendar, pattern, null, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:52:04
* @param millis
* @param pattern
* @param timeZone
* @param locale
* @return
* @return :String
*/
public static String format(long millis, String pattern, TimeZone timeZone, Locale locale){
return format(new Date(millis), pattern, timeZone, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:52:27
* @param date
* @param pattern
* @param timeZone
* @param locale
* @return
* @return :String
*/
public static String format(Date date, String pattern, TimeZone timeZone, Locale locale){
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(date);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: format
* 创建人:孙刚
* 创建时间:2014-1-21 下午05:53:32
* @param calendar
* @param pattern
* @param timeZone
* @param locale
* @return
* @return :String
*/
public static String format(Calendar calendar, String pattern, TimeZone timeZone, Locale locale){
FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale);
return df.format(calendar);
}
}
|
Defines |
java |
|
package cn.cd.sg.commons.utils;
public class Defines {
public static final String FORMAT_DATE_STRING = "yyyy-MM-dd H:m:s";
public static final String FORMAT_DATE_TIME_STRING = "HH:mm:ss";
public static final String FORMAT_TIME_STRING = "";
public static final String CONFIG_FILE_PATH = "";
}
|
CommonsUtils |
java |
|
package cn.cd.sg.commons.utils;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.lang.time.DateFormatUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import cn.cd.sg.file.utils.FileFiend;
public class CommonsUtils {
/**
* @since 获取随机数
* @param len
* @return
*/
public static String getUniqueId(int len) {
if (len < 10)
len = 10;
return getUniqueId(len, 999999999);
}
private static String getUniqueId(int length, int maxrandom) {
String tmpstr = "";
String thread = (new SimpleDateFormat("yyyyMMddhhmmssSSS"))
.format(new Date())
+ Integer.toString(getRandom(maxrandom));
thread = Integer.toString(thread.hashCode());
if (thread.indexOf("-") >= 0)
thread = thread.substring(thread.indexOf("-") + 1);
if (thread.length() < length) {
for (int i = thread.length(); i < length; i++)
tmpstr = tmpstr + "0";
thread = tmpstr + thread;
}
return thread;
}
public static int getRandom(int max) {
return (int) (Math.random() * (double) max);
}
public static Date stringToDate(String timeStr) {
Date date = new Date();
SimpleDateFormat apf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = apf.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String getCurrentDate() {
return DateFormatUtils.format(Calendar.getInstance().getTime(),
Defines.FORMAT_DATE_STRING);
}
public static String getCurrentDateTime() {
return DateFormatUtils.format(Calendar.getInstance().getTime(),
Defines.FORMAT_DATE_TIME_STRING);
}
public static Date stringToTime(String timeStr) {
Date date = new Date();
SimpleDateFormat apf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = apf.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static Calendar stringToCalendar(String timeStr) {
Date date = stringToTime(timeStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
/**
* @param
* @return
* @since 得到明天的日期 ****-**-**
*/
public static String nextDay(String today) {
@SuppressWarnings("unused")
Calendar calendar = Calendar.getInstance();
long todayLong = stringToDate(today).getTime();
long lastDayLong = todayLong + 3600000 * 24;
Date lastDay = new Date(lastDayLong);
return DateFormatUtils.format(lastDay, Defines.FORMAT_DATE_STRING);
}
/**
* 将日期分解获得连串的日期
*
* @param startDate
* @param endDate
* @return
* @since
*/
@SuppressWarnings("unchecked")
public static List getDays(String startDate, String endDate) {
List list = new ArrayList();
if (startDate.equals(endDate))
list.add(startDate);
else {
for (String date = startDate; !date.equals(endDate); date = CommonsUtils.nextDay(date)) {
list.add(date);
}
list.add(endDate);
}
return list;
}
@SuppressWarnings("deprecation")
public static String[] getUpdateTime() {
Date date = Calendar.getInstance().getTime();
date.setMinutes(date.getMinutes() + 1);
String[] returnTime = new String[2];
returnTime[0] = DateFormatUtils.format(date,
Defines.FORMAT_DATE_TIME_STRING);
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
returnTime[1] = DateFormatUtils.format(date,
Defines.FORMAT_DATE_TIME_STRING);
return returnTime;
}
/**
* 讲时间分解成小时
*
* @param beginTime
* @param endTime
* @return
* @since
*/
public static int[] getTimesString(String beginTime, String endTime) {
int s1 = Integer.parseInt(beginTime.split(":")[0]);
int s2 = Integer.parseInt(endTime.split(":")[0]);
int[] back = new int[s2 - s1 + 1];
for (int i = 0; i < back.length; i++) {
back[i] = s1 + i;
}
return back;
}
/**
* 根据某年的某一月,获取该月的所有日期
*
* @param date
* 格式yyyy-MM
* @return
* @since
*/
@SuppressWarnings("unchecked")
public static List getDatesList(String date) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM");
Calendar time = Calendar.getInstance();
time.clear();
Date d1 = format.parse(date);
time.setTime(d1);
int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);
DateFormat formats = new SimpleDateFormat(Defines.FORMAT_DATE_STRING);
List list = new ArrayList();
for (int i = 1; i <= day; i++) {
String s = format.format(d1) + "-" + i;
Date sss = formats.parse(s);
String dd = formats.format(sss);
list.add(dd);
}
return list;
}
/**
* 按照HH:mm:ss的格式截断字符串获取广告播放时间长度
*
* @param beginTime
* @param endTime
* @return
* @since
*/
public static String getPlayTime(String beginTime, String endTime) {
int begin = Integer.parseInt(beginTime.split(":")[0]);
int end = Integer.parseInt(endTime.split(":")[0]);
return String.valueOf(end - begin);
}
public static Date stringToTime(String timeStr, String formatString) {
Date date = new Date();
SimpleDateFormat apf = new SimpleDateFormat(formatString);
try {
date = apf.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
@SuppressWarnings("unchecked")
public static List sortList(List list, String name) {
Comparator namCompare = new BeanComparator(name);
Collections.sort(list, namCompare);
return list;
}
/**
* @since int --> byte
* @param number
* @param byteSum
* @return
*/
public static byte[] convertBytes(int number, int byteSum) {
byte[] b = new byte[byteSum];
int len = b.length;
for (int i = 0; i < len; i++) {
b[len - i - 1] = (byte) ((number >> ((i) * 8)) & 0xFF);
}
return b;
}
public static String getCurrentTime() {
return DateFormatUtils.format(Calendar.getInstance().getTime(),
Defines.FORMAT_TIME_STRING);
}
public static String next59Secends(String beginTime) {
Date begin = new Date();
try {
begin = new SimpleDateFormat(Defines.FORMAT_TIME_STRING)
.parse(beginTime);
} catch (ParseException e) {
e.printStackTrace();
}
long nextMinute = begin.getTime() + 59000;
return DateFormatUtils.format(nextMinute, Defines.FORMAT_TIME_STRING);
}
/**
* Task:比较日期1是否在日期2之前(包括)
* @since
* @param date1日期字符串1
* @param date2日期字符串2
* @return 日期1在日期2之前返回true,否则返回false
*/
public static boolean isNotAfter(String date1,String date2){
return stringToDate(date1).before(stringToDate(date2))||stringToDate(date1).equals(stringToDate(date2));
}
/**
* Task:比较时间1是否在时间2之前(包括)
* @since
* @param time1时间字符串1
* @param time2时间字符串2
* @param formatString时间格式
* @return 时间1在时间2之前返回true,否则返回false
*/
public static boolean isNotAfter(String time1,String time2,String formatString){
return stringToTime(time1, formatString).before(stringToTime(time2, formatString))||stringToTime(time1, formatString).equals(stringToTime(time2, formatString));
}
/**
* Task:比较两个时间字符串的天数间隔
* @since
* @param s1时间字符串1
* @param s2时间字符串2
* @return 间隔天数,负数表示s1在s2之前,正数表示s1在s2之后
*/
public int compareDate(String s1,String s2){
Date date1=stringToDate(s1);
Date date2=stringToDate(s2);
return (int)(date1.getTime()-date2.getTime())/(24*3600*1000);
}
/**
* 获得项目的物理地址路径(最后一个字符是分隔符).
*
* @return
* @author sunny
* @create 2007-10-25 下午03:44:40
*/
public static String getAbsPathOfProject() {
String url = CommonsUtils.class.getClassLoader().getResource("").toString();
String reg = "file:(.+)WEB-INF";
Matcher mat = Pattern.compile(reg, Pattern.CASE_INSENSITIVE).matcher(
url);
if (mat.find()) {
String path = mat.group(1);
path = path.replaceAll("/", "\\" + File.separator);
if (File.separator.equals("\\"))// windows
return path.substring(1);
return path;
}
return null;
}
/**
* 将字节转为Sring字符串
*
* @param data
* @return
*/
public static String base64CodeByteTo64String(byte[] data) {
BASE64Encoder encoder = new BASE64Encoder();
if (data == null) {
System.out.println("not get the img!");
return null;
}
return encoder.encode(data).replaceAll("\\s*","");
}
/**
* 将string类型的数据转码为byte类型.
*
* @param fileData
* String 类型的数据.
* @return 转码后的数据byte类型,发生异常或者filedate为null时返回null.
*/
public static byte[] base64CodeDecode(String fileData) {
if (fileData == null) {
return null;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
return decoder.decodeBuffer(fileData);
} catch (IOException e) {
e.printStackTrace();
System.out.println(e.toString());
}
return null;
}
/**
* 将zip文件转成Base64编码字符串
* @param filePath
* @return
* @author pengcc
*/
public static String getBase64StringOfZipFile(String filePath){
byte[] data=FileFiend.readFileByte(filePath);
return CommonsUtils.base64CodeByteTo64String(data);
}
/**
* 将放在List里所有String用","连接起来
* @author huangfei
* @create 2009-6-24 下午03:02:00
* @since
* @param StringList
* @return
*/
@SuppressWarnings("unchecked")
public static String splitListWithComma(List StringList){
StringBuffer strOfList = new StringBuffer("");
for(int i=0;i<StringList.size();i++){
if(i!=0){
strOfList.append(",");
}
strOfList.append(StringList.get(i).toString());
}
return strOfList.toString();
}
}
|
LocaleUtils |
java |
|
package cn.cd.sg.collection.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unchecked")
public class LocaleUtils {
private static List cAvailableLocaleList;
private static Set cAvailableLocaleSet;
private static final Map cLanguagesByCountry = Collections.synchronizedMap(new HashMap());
private static final Map cCountriesByLanguage = Collections.synchronizedMap(new HashMap());
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: toLocale
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:27:23
* @param str
* @return :Locale
*/
public static Locale toLocale(String str) {
if (str == null){
return null;
}
int len = str.length();
if (len != 2 && len != 5 && len < 7){
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z'){
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2){
return new Locale(str, "");
}
if (str.charAt(2) != '_'){
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch3 = str.charAt(3);
if (ch3 == '_'){
return new Locale(str.substring(0, 2), "", str.substring(4));
}
char ch4 = str.charAt(4);
if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z'){
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5){
return new Locale(str.substring(0, 2), str.substring(3, 5));
}
if (str.charAt(5) != '_'){
throw new IllegalArgumentException("Invalid locale format: " + str);
}else{
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: localeLookupList
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:27:30
* @param locale
* @return :List
*/
public static List localeLookupList(Locale locale){
return localeLookupList(locale, locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: localeLookupList
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:27:57
* @param locale
* @param defaultLocale
* @return :List
*/
public static List localeLookupList(Locale locale, Locale defaultLocale){
List list = new ArrayList(4);
if(locale != null){
list.add(locale);
if(locale.getVariant().length() > 0){
list.add(new Locale(locale.getLanguage(), locale.getCountry()));
}
if(locale.getCountry().length() > 0){
list.add(new Locale(locale.getLanguage(), ""));
}
if(!list.contains(defaultLocale)){
list.add(defaultLocale);
}
}
return Collections.unmodifiableList(list);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: availableLocaleList
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:29:45
* @return :List
*/
public static List availableLocaleList(){
if(cAvailableLocaleList == null){
initAvailableLocaleList();
}
return cAvailableLocaleList;
}
private static synchronized void initAvailableLocaleList(){
if(cAvailableLocaleList == null){
List list = Arrays.asList(Locale.getAvailableLocales());
cAvailableLocaleList = Collections.unmodifiableList(list);
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: availableLocaleSet
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:31:42
* @return :Set
*/
public static Set availableLocaleSet(){
if(cAvailableLocaleSet == null){
initAvailableLocaleSet();
}
return cAvailableLocaleSet;
}
private static synchronized void initAvailableLocaleSet(){
if(cAvailableLocaleSet == null){
cAvailableLocaleSet = Collections.unmodifiableSet(new HashSet(availableLocaleList()));
}
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: isAvailableLocale
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:33:22
* @param locale
* @return :boolean
*/
public static boolean isAvailableLocale(Locale locale){
return availableLocaleList().contains(locale);
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: languagesByCountry
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:33:44
* @param countryCode
* @return :List
*/
public static List languagesByCountry(String countryCode){
List langs = (List)cLanguagesByCountry.get(countryCode);
if(langs == null){
if(countryCode != null){
langs = new ArrayList();
List locales = availableLocaleList();
for(int i = 0; i < locales.size(); i++){
Locale locale = (Locale)locales.get(i);
if(countryCode.equals(locale.getCountry()) && locale.getVariant().length() == 0){
langs.add(locale);
}
}
langs = Collections.unmodifiableList(langs);
}else {
langs = Collections.EMPTY_LIST;
}
cLanguagesByCountry.put(countryCode, langs);
}
return langs;
}
/**
* 描述 : (这里用一句话描述这个方法的作用)
* 方法名: countriesByLanguage
* 创建人:孙刚
* 创建时间:2014-1-22 上午10:35:52
* @param languageCode
* @return :List
*/
public static List countriesByLanguage(String languageCode){
List countries = (List)cCountriesByLanguage.get(languageCode);
if(countries == null){
if(languageCode != null){
countries = new ArrayList();
List locales = availableLocaleList();
for(int i = 0; i < locales.size(); i++){
Locale locale = (Locale)locales.get(i);
if(languageCode.equals(locale.getLanguage()) && locale.getCountry().length() != 0 && locale.getVariant().length() == 0){
countries.add(locale);
}
}
countries = Collections.unmodifiableList(countries);
}else {
countries = Collections.EMPTY_LIST;
}
cCountriesByLanguage.put(languageCode, countries);
}
return countries;
}
}
|