字符数组转String
package com.sunsheen.hcc.fabric.utils;
/**
* 字符数组工具
* @author WangSong
*
*/
public class ByteArryUtil {
/**
* 字节数组转成16进制表示格式的字符串
*
* @param byteArray
* 需要转换的字节数组
* @return 16进制表示格式的字符串
**/
public static String toHexString(byte[] byteArray) {
if (byteArray == null || byteArray.length < 1)
throw new IllegalArgumentException("this byteArray must not be null or empty");
final StringBuilder hexString = new StringBuilder();
for (int i = 0; i < byteArray.length; i++) {
if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零
hexString.append("0");
hexString.append(Integer.toHexString(0xFF & byteArray[i]));
}
return hexString.toString().toLowerCase();
}
}
json、map、list、String格式数据互转
package com.sunsheen.hcc.fabric.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.ListOrderedMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
/**
* json工具
* @author WangSong
*
*/
public class JsonParseUtil {
/**
* 將jsonArry字符串转换成map(里面可能是多个对象的情况)
* @param json
* @return
*/
public static List<Map<String, Object>> parseJSON2List(String json) {
JSONArray jsonArr = JSONArray.fromObject(json);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = jsonArr.iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(parseJSON2Map(json2.toString()));
}
return list;
}
private static Map<String, Object> parseJSON2Map(String jsonStr) {
ListOrderedMap map = new ListOrderedMap();
// 最外层解析
JSONObject json = JSONObject.fromObject(jsonStr);
for (Object k : json.keySet()) {
Object v = json.get(k);
// 如果内层还是数组的话,继续解析
if (v instanceof JSONArray) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Iterator<JSONObject> it = ((JSONArray) v).iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(parseJSON2Map(json2.toString()));
}
map.put(k.toString(), list);
} else {
map.put(k.toString(), v);
}
}
Iterator iterator = map.keySet().iterator();
List<String> lsList = new ArrayList<String>();
int d=0;
while (iterator.hasNext()) {
String key = (String) iterator.next();
Object object = map.get(key);
// 进行遍历删除,当值为空的时候删除这条数据
if (object.equals("")) {
iterator.remove();
map.remove(key);
}
}
return map;
}
/**
* 将对象转换成json
* @param param
* @return
*/
public static String object2Json(Object param){
// JSON.toJSONString();
JSONObject jsonObject = JSONObject.fromObject(param);
return jsonObject.toString();
}
/**
* 将json字符串转换成map
* @param json
* @return
*/
public static Map<String, Object> json2Map(String json) {
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(json);
Map<String, Object> valueMap = new HashMap<String, Object>();
valueMap.putAll(jsonObject);
return valueMap;
}
/**
* list对象转换成json
* @param param
* @return
*/
public static String list2String(List param){
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
JSONArray json = JSONArray.fromObject(param, jsonConfig);
return json.toString();
}
}
实体对象转换成map
Contract contract = new Contract ();
try{
Map<String, Object> params = new HashMap<String, Object>();
//将对象信息封装到map
Class clazz = contract.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
String name = f.getName();//当前字段
if(name.equals("serialVersionUID"))
continue;
PropertyDescriptor descriptor = new PropertyDescriptor(name, clazz);//得到当前字段信息
Method readMethod = descriptor.getReadMethod();
Object value = readMethod.invoke(contract);//得到当前字段值
if(null != value)
params.put(name, value);
前后端数据格式转换
package com.sunsheen.hcc.fabric.utils;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import com.sunsheen.edu.case1.entity.ResponseMsg;
import com.sunsheen.jfids.commons.beanutils.BeanUtils;
import com.sunsheen.jfids.commons.beanutils.ConvertUtils;
import com.sunsheen.jfids.commons.beanutils.converters.DateConverter;
import com.sunsheen.jfids.gson.Gson;
/**
* 前后端数据转换工具类
* @author WangSong
*
*/
public class WebUtils {
/**
* 把request对象中的请求参数封装到bean中
* @param request http请求
* @param clazz 需要存入信息的对象class
* @return
*/
public static <T> T request2Bean(HttpServletRequest request,Class<T> clazz){
try{
T bean = clazz.newInstance();
Enumeration e = request.getParameterNames();
while(e.hasMoreElements()){
String name = (String) e.nextElement();
String value = request.getParameter(name);
if(null != value && !"".equals(value)){
//日期注册
if(value.contains("-")){
DateConverter converter = new DateConverter();
converter.setPattern("yyyy-MM-dd");
ConvertUtils.register(converter,Date.class);
}
//对象赋值
BeanUtils.setProperty(bean, name, value);
}
}
return bean;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 响应到页面的数据
* @param code
* @param data
* @return
*/
public static String responseMsg(Integer code, Object data) {
ResponseMsg msg = new ResponseMsg(data,code);
return new Gson().toJson(msg);
}
/**
* 响应到页面的数据
* @param data
* @return
*/
public static String responseMsg(Object data) {
ResponseMsg msg = new ResponseMsg(data);
return new Gson().toJson(msg);
}
}
得到指定文件夹大小
package com.sunsheen.jfids.studio.monitor.utils.local;
import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* 得到指定文件夹大小
* @author WangSong
*
*/
public class FileUtil {
private ExecutorService service;
final private AtomicLong pendingFileVisits = new AtomicLong();
/** 通过CountdownLatch 得到文件夹大小的初始常量 **/
final private AtomicLong totalSize = new AtomicLong();
final private CountDownLatch latch = new CountDownLatch(1);
/** 通过BlockingQueue得到文件夹大小的初始常量 **/
final private BlockingQueue<Long> fileSizes = new ArrayBlockingQueue<Long>(500);
/////////////////////////////////////CountdownLatch/////////////////////////////////////////
//更新文件总大小(多线程)
private void updateTotalSizeOfFilesInDir(final File file) {
long fileSize = 0;//初始化文件大小
//文件,直接返回大小
if (file.isFile())
fileSize = file.length();
//文件夹,遍历所有文件总大小
else {
final File[] children = file.listFiles();
if(null == children){
totalSize.set(0);
return;
}
for (final File child : children) {
//文件:直接加当前文件的大小
if (child.isFile())
fileSize += child.length();
//文件夹:遍历里面的文件的大小
else {
pendingFileVisits.incrementAndGet();//增加一个当前值(用来观察这里的线程是否启动)
service.execute(new Runnable() {
public void run() {
updateTotalSizeOfFilesInDir(child);
}
});
}
}
}
totalSize.addAndGet(fileSize);
//如果没有遍历的子文件夹,则pendingFileVisits-1 = 0,当前线程等待
if (pendingFileVisits.decrementAndGet() == 0)
latch.countDown();//发令枪 - 1
}
/**
* 得到指定文件的大小
* @param fileName 文件名(全路径)
* @return 文件夹大小(M)
* @throws InterruptedException
*/
public double getTotalSizeOfFile(final String filePath){
service = Executors.newCachedThreadPool();//初始化线程池
pendingFileVisits.incrementAndGet();//增加当前值1
double result = 0;//初始化结果
try {
updateTotalSizeOfFilesInDir(new File(filePath));
latch.await(100, TimeUnit.SECONDS);//当前线程等待,直到锁存器计数到0
// latch.await();
//将k转换成m
long resultK = totalSize.longValue();
BigDecimal bdK = new BigDecimal(resultK);
BigDecimal bdM = bdK.divide(new BigDecimal(1024 * 1024)).setScale(5, RoundingMode.HALF_UP);//保留5位小数
result = bdM.doubleValue();
}catch (InterruptedException e) {
e.printStackTrace();
}finally {
service.shutdown();
}
return result;
}
/////////////////////////////////////CountdownLatch/////////////////////////////////////////
/////////////////////////////////////BlockingQueue/////////////////////////////////////////
private void startExploreDir(final File file) {
pendingFileVisits.incrementAndGet();//記錄遍历文件夹次数
service.execute(new Runnable() {
public void run() {
exploreDir(file);
}
});
}
private void exploreDir(final File file) {
long fileSize = 0;
if (file.isFile())
fileSize = file.length();
else {
final File[] children = file.listFiles();
if (children != null)
for (final File child : children) {
if (child.isFile())
fileSize += child.length();
else {
startExploreDir(child);
}
}
}
try {
fileSizes.put(fileSize);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
pendingFileVisits.decrementAndGet();
}
/**
* 得到指定文件的大小
* @param fileName
* @return
* @throws InterruptedException
*/
public double getTotalSizeOfFile1(final String fileName){
service = Executors.newFixedThreadPool(100);
double result = 0;
try {
startExploreDir(new File(fileName));
long totalSize = 0;
while (pendingFileVisits.get() > 0 || fileSizes.size() > 0) {
final Long size = fileSizes.poll(10, TimeUnit.SECONDS);
totalSize += size;
}
//将k转换成m
BigDecimal bdK = new BigDecimal(totalSize);
BigDecimal bdM = bdK.divide(new BigDecimal(1024 * 1024)).setScale(5, RoundingMode.HALF_UP);//保留5位小数
result = bdM.doubleValue();
}catch(Exception e){
e.printStackTrace();
}finally {
service.shutdown();
}
return result;
}
/////////////////////////////////////BlockingQueue/////////////////////////////////////////
/**
* 先根遍历序递归删除文件夹
*
* @param dirFile 要被删除的文件或者目录
* @return 删除成功返回true, 否则返回false
*/
public boolean deleteFile(File dirFile) {
// 如果dir对应的文件不存在,则退出
if (!dirFile.exists()) {
return false;
}
if (dirFile.isFile()) {
return dirFile.delete();
} else {
for (File file : dirFile.listFiles()) {
deleteFile(file);
}
}
return dirFile.delete();
}
}
遍历指定文件夹下存在log日志文件的文件夹
package com.sunsheen.jfids.studio.monitor.utils.local;
import java.io.File;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import com.sunsheen.jfids.studio.monitor.common.LogInfo;
/**
* 遍历当前eclipse运行空间下所有项目名跟对应日志
* @author WangSong
*
*/
public class LocalLogUtil {
private LocalLogUtil(){}
/**
* 遍历出存在项目日志文件的文件夹
* @return
*/
public static Map<String,Set<File>> getPlugLogs(){
Map<String,Set<File>> associatedLogMap = new ConcurrentHashMap<String,Set<File>>();//
//截取出正确的运行空间目录
String runtimeSpace = LogInfo.RUNTIME_SPACE.substring(1,LogInfo.RUNTIME_SPACE.length() - 1);
String[] arr = runtimeSpace.split("/");
StringBuffer sb = new StringBuffer();
for(String space : arr)
sb.append(space+File.separator);
String logParentFolder = sb + LogInfo.LOG_PARENT_PATH;
File file = new File(logParentFolder);//存放所有日志文件的文件夹
listExistingLogFolder(associatedLogMap,file);
return associatedLogMap;
}
//遍历当前文件夹下面所有文件
private static void listExistingLogFolder(Map<String,Set<File>> associatedLogMap,File file){
//遍历当前文件夹
File[] innerFiles = file.listFiles();
for(File result : innerFiles){
//存放对应关系
if(result.isDirectory())
listExistingLogFolder(associatedLogMap,result);
else{
String name = result.getName();//当前文件名
//是日志文件,存入
if(name.contains(".log")){
String projectName = result.getParent();//上层项目名路径
//如果不是项目日志文件不记录
if(!projectName.contains("com.sunsheen.jfids"))
continue;
//截取出正确的插件项目名
projectName = projectName.substring(projectName.lastIndexOf("c"));
//保证能添加所有的日志文件
if(associatedLogMap.containsKey(projectName)){
//当前项目存在日志文件时
Set<File> currentLogs = associatedLogMap.get(projectName);
currentLogs.add(result);
associatedLogMap.put(projectName, currentLogs);//保存最新的关系
}else{
//不存在当前项目日志文件时
Set<File> currentLogs = new HashSet<File>();
currentLogs.add(result);
associatedLogMap.put(projectName,currentLogs);//创建一个新关联
}
}
}
}
}
}
除了上述介绍外,还有一些Java常用工具类,以后大家都会接触到。