字符數組轉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> parseJSON2List(String json) {
JSONArray jsonArr = JSONArray.fromObject(json);
List> list = new ArrayList>();
Iterator it = jsonArr.iterator();
while (it.hasNext()) {
JSONObject json2 = it.next();
list.add(parseJSON2Map(json2.toString()));
}
return list;
}
private static Map 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> list = new ArrayList>();
Iterator 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 lsList = new ArrayList();
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 json2Map(String json) {
com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(json);
Map valueMap = new HashMap();
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 params = new HashMap();
//將對象信息封裝到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 request2Bean(HttpServletRequest request,Class 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 fileSizes = new ArrayBlockingQueue(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> getPlugLogs(){
Map> associatedLogMap = new ConcurrentHashMap>();//
//截取出正確的運行空間目錄
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> 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 currentLogs = associatedLogMap.get(projectName);
currentLogs.add(result);
associatedLogMap.put(projectName, currentLogs);//保存最新的關系
}else{
//不存在當前項目日志文件時
Set currentLogs = new HashSet();
currentLogs.add(result);
associatedLogMap.put(projectName,currentLogs);//創建一個新關聯
}
}
}
}
}
}

除了上述介紹外,還有一些Java常用工具類,以后大家都會接觸到。