package tmbf.nothing.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.BufferedReader;
import java.io.Reader;
import java.sql.Clob;
/**
* @ClassName:
* @Description: 字符串工具类
* @author yanbxa
* @date
*/
public class StringUtil {
/**
*@Title: isEmptyString
*@Description: 判断一个字符串是否为:NULL、空字符串、"null"、"NULL"、
*@Author: yanbxa
*@Param: [value]
*@Return: boolean
*@Date: 2019/11/26 10:42
**/
public static boolean isEmptyString(String value) {
if (value == null) { // NULL
return true;
}
if (value.trim().length() < 1) { // 空字符串
return true;
}
if ("null".equalsIgnoreCase(value.trim())) { // "null"、"NULL"
return true;
}
return false;
}
/**
*@Title: splitStrToArrayByLength
*@Description: 将字符串拆分成多个相等长度的字符串数组
*@Author: yanbxa
*@Param: [str, eachLength]
*@Return: java.lang.String[]
*@Date: 2019/11/26 10:55
**/
public static String[] splitStrToArrayByLength(String str, int eachLength) {
if (eachLength < 1) {
return new String[] { str };
}
int remainder = str.length() % eachLength; // 余数
int merchant = str.length() / eachLength; // 商
int arraySize = merchant;
if (remainder > 0) {
arraySize = arraySize + 1;
}
String[] array = new String[arraySize];
for (int i = 0; i < arraySize; i++) {
int startIndex = i * eachLength;
int endIndex;
if (i < arraySize - 1) {
endIndex = (i + 1) * eachLength;
} else {
endIndex = str.length();
}
array[i] = str.substring(startIndex, endIndex);
}
return array;
}
/**
*@Title: toJSONStringWithNullValue
*@Description: 将对象转为JSON字符串[map中value为null也会生成key、string类型的null转为""空字符串、null数字类型转为0]
*@Author: yanbxa
*@Param: [object]
*@Return: java.lang.String
*@Date: 2019/11/26 10:50
**/
public static String toJSONStringWithNullValue(Object object) {
return JSON.toJSONString(object, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero);
}
/**
*@Title: ClobToString
*@Description: 大字段转String
*@Author: yanbxa
*@Param: [clob]
*@Return: java.lang.String
*@Date: 2019/12/2 10:52
**/
public static String ClobToString(Clob clob) {
String reString = "";
Reader is = null;
BufferedReader br = null;
try {
is = clob.getCharacterStream();
br = new BufferedReader(is);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
sb.append("\r\n"); // 换行
s = br.readLine();
}
reString = sb.toString();
} catch (Exception e) {
return reString;
} finally {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return reString;
}
public static void main(String[] args) {
// 测试方法
System.out.println(isEmptyString(null));
System.out.println(isEmptyString(" "));
System.out.println(isEmptyString("null"));
System.out.println(toJSONStringWithNullValue(new String[] { "123", "234" }));
System.out.println(toJSONStringWithNullValue(splitStrToArrayByLength("123456789", 4)));
}
}