概述
自上而下工具类为
- 集合工具类
- 文件工具类
- 随机字符串生成器
- String工具类
集合操作日常工具
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.Function;
/**
* 集合操作日常工具
*/
public class CollectionUtils {
public static final Function ASSIGN = new Function() {
@Override
public Object apply(Object o) {
return o;
}
};
public static <T> List<T> copyList(Collection<T> input) {
return convertList(input, new Function<T, T>() {
@Override
public T apply(T o) {
return o;
}
});
}
/**
* 复制并转换List
*
* @param input
* @param converter
* @param <T1>
* @param <T2>
* @return
*/
public static <T1, T2> List<T2> convertList(Collection<T1> input, Function<T1, T2> converter) {
List<T2> result = new ArrayList<T2>();
if (input == null) {
return result;
}
for (T1 a : input) {
T2 a2 = converter.apply(a);
if (a2 != null) {
result.add(a2);
}
}
return result;
}
/**
* @param input
* @param convertor
* @param <T1>
* @param <T2>
* @return
*/
public static <T1, T2> List<T2> convertList(T1[] input, Function<T1, T2> convertor) {
List<T2> result = new ArrayList<T2>();
if (input == null) {
return result;
}
for (T1 a : input) {
T2 a2 = convertor.apply(a);
if (a2 != null) {
result.add(a2);
}
}
return result;
}
/**
* 转换数组
*
* @param input
* @param convertor
* @param <T1>
* @param <T2>
* @return
*/
public static <T1, T2> T2[] convertArray(T1[] input, Function<T1, T2> convertor) {
if (input == null || input.length == 0) {
return null;
}
List<T2> result = new ArrayList<T2>();
for (T1 v : input) {
result.add(convertor.apply(v));
}
if (result.size() == 0) {
return null;
}
T2[] r = (T2[]) Array.newInstance(result.get(0).getClass(), result.size());
result.toArray(r);
return r;
}
/**
* 单纯的复制map
*
* @param input
* @param <K>
* @param <V>
* @return
*/
public static <K, V> Map<K, V> copyMap(Map<K, V> input) {
return convertMapValues(input, new Function<V, V>() {
@Override
public V apply(V o) {
return o;
}
});
}
/**
* 复制并转换Map
*
* @param input
* @param convertor
* @param <K>
* @param <V1>
* @param <V2>
* @return
*/
public static <K, V1, V2> Map<K, V2> convertMapValues(Map<K, V1> input, Function<V1, V2> convertor) {
Map<K, V2> result = new HashMap<K, V2>();
if (input == null) {
return result;
}
for (Map.Entry<K, V1> e : input.entrySet()) {
result.put(e.getKey(), convertor.apply(e.getValue()));
}
return result;
}
/**
* 合并两组Keys
*
* @param set1
* @param set2
* @param <K>
* @return
*/
public static <K> Collection<K> mergeKeys(Collection<K> set1, Collection<K> set2) {
HashSet<K> keys = new HashSet<K>();
for (K k : set1) {
keys.add(k);
}
for (K k : set2) {
keys.add(k);
}
return keys;
}
/***
* 排序
* @param list
* @param <E>
* @return
*/
public static <E extends Comparable<E>> Collection<E> sortList(Collection<E> list) {
List<E> result = CollectionUtils.convertList(list, new Function<E, E>() {
@Override
public E apply(E e) {
return e;
}
});
result.sort(new Comparator<E>() {
@Override
public int compare(E e, E o) {
return e.compareTo(o);
}
});
return result;
}
/**
* 合并数组元素
*
* @param array
* @param elements
* @param <E>
* @return
*/
public static <E> E[] mergeArray(E[] array, E... elements) {
List<E> list = new ArrayList<E>();
if (array != null) {
for (E a : array) {
list.add(a);
}
}
for (E a : elements) {
if (a != null) {
list.add(a);
}
}
if (list.size() == 0) {
return array;
} else {
E[] result = (E[]) Array.newInstance(list.get(0).getClass(), list.size());
list.toArray(result);
return result;
}
}
/**
* 转为','分割的字符串
* @param objects
* @param <E>
* @return
*/
public static <E> String toString(Iterable<E> objects) {
if (objects == null) {
return "[]";
}
StringBuilder str = new StringBuilder();
for (Object o : objects) {
str.append(o != null ? o.toString() : "").append(",");
}
if (str.length() > 0) {
return str.substring(0, str.length() - 1);
} else {
return "";
}
}
}
文件操作工具类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* 文件相关帮助类
*/
public class FileUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/**
* 将当前的pid写入到文件中
* @param filename
*/
public static void writeCurrentPid(String filename) {
String name = ManagementFactory.getRuntimeMXBean().getName();
System.out.println(name);
String pid = name.split("@")[0];
try {
FileOutputStream fs = new FileOutputStream(filename, false);
fs.write(pid.getBytes());
fs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 重命名文件
* @param oldFile
* @param newFile
* @throws IOException
*/
public static boolean renameFile(String oldFile, String newFile) throws IOException {
File file = new File(oldFile);
File file2 = new File(newFile);
if (file2.exists()) {
throw new IOException("file exists:" + newFile);
}
boolean success = file.renameTo(file2);
LOGGER.info("<<<FILE>>> rename file from {} to {} success={}", oldFile, newFile, success);
return success;
}
/**
* 从文件中读取
* @param filename
* @return
*/
public static String readFromFile(String filename, String encoding) {
Path path = Paths.get(filename);
try {
byte[] buffer = Files.readAllBytes(path);
return new String(buffer, encoding);
} catch (IOException e) {
throw new IllegalArgumentException("readFromFile failed:" + filename, e);
}
}
/**
* 从文件中读取
* @param filename
* @return
*/
public static byte[] readFromFile(String filename) {
Path path = Paths.get(filename);
try {
byte[] buffer = Files.readAllBytes(path);
return buffer;
} catch (IOException e) {
throw new IllegalArgumentException("readFromFile failed:" + filename, e);
}
}
/**
*
* @param stream
* @return
*/
public static String readFromStream(InputStream stream) {
return readFromStream(stream, "UTF-8");
}
/**
* 从InputStream中按
* @param stream
* @return
*/
public static String readFromStream(InputStream stream, String encoding) {
try {
ByteArrayOutputStream arr = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
while (true) {
int len = stream.read(buffer);
if (len > 0) {
arr.write(buffer, 0, len);
} else {
break;
}
}
return new String(arr.toByteArray(), encoding);
} catch (Exception ex) {
throw new RuntimeException("readStream failed", ex);
}
}
/**
* 写文件
* @param name
* @param content
* @throws IOException
*/
public static void writeFile(String name, String content) throws IOException {
LOGGER.info("<<<FILE>>> write file {}", name);
FileWriter writer = new FileWriter(name, false);
BufferedWriter out = new BufferedWriter(writer);
out.write(content);
out.close();
}
/**
* 删除文件, 文件不存在返回false, 删除失败抛异常
*
* @param name
* @return
*/
public static boolean deleteFile(String name) {
File file = new File(name);
if (!file.exists()) {
LOGGER.info("<<<FILE>>> delete file {} NOT EXISTS", name);
return false;
}
boolean success = file.delete();
LOGGER.info("<<<FILE>>> delete file {} success={}", name, success);
return success;
}
public static void mkdir(String s) {
File f = new File(s);
if (!f.exists()) {
f.mkdir();
LOGGER.info("<<<FILE>>> mkdir {}", s);
} else if (!f.isDirectory()) {
LOGGER.info("<<<FILE>>> mkdir {} failed, type conflicted", s);
throw new IllegalArgumentException("path already exists" + s);
}
}
}
随机字符串生成器
public class StringGenerator {
public static int MAX_RETRYS = 200;
public static String LOWERCASE_CHARS = "abcdefghijklmnopqrstuvwxyz";
public static String UPPERCASE_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String NUMBERS = "0123456789";
public static String SPECIALS = ".:+=^!/*?&<>()[]{}@%#";
public static String BASIC = LOWERCASE_CHARS + NUMBERS;
public static String WITH_UPPERCASE = BASIC + UPPERCASE_CHARS;
public static String WITH_SPECIALS = WITH_UPPERCASE + SPECIALS;
public static Random RANDOM = new Random(System.currentTimeMillis());
public static String generate(int length) {
return generate(BASIC, length, true, true, false, false);
}
public static String generateWithUppercase(int length) {
return generate(WITH_UPPERCASE, length, true, true, true, false);
}
public static String generateWithSpecial(int length) {
return generate(WITH_SPECIALS, length, true, true, true, true);
}
private static String generate(String chars, int length, boolean lower, boolean numbers, boolean upper, boolean specials) {
for (int k = 0; k < MAX_RETRYS; k++) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < length; i++) {
str.append(chars.charAt(RANDOM.nextInt(chars.length())));
}
String s = str.toString();
if (test(s, lower, numbers, upper, specials)) {
return s;
}
}
throw new RuntimeException("Over max generator retrys");
}
private static boolean test(String s, boolean lower, boolean numbers, boolean upper, boolean specials) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (lower && LOWERCASE_CHARS.indexOf(c) >= 0) {
lower = false;
}
if (numbers && NUMBERS.indexOf(c) >= 0) {
numbers = false;
}
if (upper && UPPERCASE_CHARS.indexOf(c) >= 0) {
upper = false;
}
if (specials && SPECIALS.indexOf(c) >= 0) {
specials = false;
}
}
return !(lower || numbers || upper || specials);
}
}
string操作工具类
/**
* String Utils
* 尽量使用本类,不要引入多个包的StringUtils
*/
public class StringUtils {
public static final String EMPTY = "";
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
/**
* 判断是否null或""
*
* @param str
* @return
*/
public static boolean isEmpty(String str) {
return str == null ? true : str.length() == 0;
}
/**
* 去除空格后是否仍然为空
* @param s
* @return
*/
public static boolean isBlank(String s) {
if (isEmpty(s)) {
return true;
}
return s.trim().length() == 0;
}
/**
* 安全的toString,增加空的判断
* @param v
* @return
*/
public static String toString(Object v) {
return toString(v, EMPTY);
}
/**
* 安全的toString,增加空的判断
* @param v
* @param nullStr
* @return
*/
public static String toString(Object v, String nullStr) {
if (v == null) {
return nullStr;
} else {
return v.toString();
}
}
public static String toString(String[] array) {
if (array == null || array.length == 0) {
return "";
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0) {
str.append(",");
}
str.append(array[i]);
}
return str.toString();
}
public static byte[] getBytes(String s) {
return getBytes(s, DEFAULT_CHARSET);
}
public static byte[] getBytes(String s, Charset charset) {
return s.getBytes(charset);
}
public static String getString(byte[] buffer) {
return getString(buffer, DEFAULT_CHARSET);
}
public static String getString(byte[] buffer, Charset charset) {
if (buffer == null) {
return EMPTY;
}
return new String(buffer, charset);
}
/**
* 比较两个字符串是否相等
* @param lv
* @param rv
* @return
*/
public static boolean equals(String lv, String rv) {
if (lv == null) {
return rv == null;
} else {
if (rv == null) {
return false;
} else {
return lv.equals(rv);
}
}
}
public static String repeat(String s, int n) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
str.append(s);
}
return str.toString();
}
/**
* 打马赛克
*
* @param s
* @param leftChars
* @return
*/
public static String mosaicString(String s, int leftChars) {
if (StringUtils.isEmpty(s)) {
return s;
}
int n = s.length() - leftChars;
if (n > 0) {
return StringUtils.repeat("*", n) + s.substring(n);
} else {
return StringUtils.repeat("*", s.length());
}
}
/**
* 打马赛克
*
* @param s
* @param leftChars
* @return
*/
public static String mosaicString(String s, int startChars, int leftChars) {
if (StringUtils.isEmpty(s)) {
return s;
}
if (s.length() >= startChars) {
return s.substring(0, 2) + mosaicString(s.substring(2), leftChars);
} else {
return StringUtils.repeat("*", s.length());
}
}
/**
* Get String suffix with length `n`
* @param s
* @param n
* @return
*/
public static String getSuffix(String s, int n) {
if (isEmpty(s)) {
return "";
} else if (s.length() < n) {
return s;
} else {
return s.substring(s.length() - n);
}
}
/**
*
* @param buffer
* @param limitLength
* @return
*/
public static String bufferToString(byte[] buffer, int limitLength) {
if (buffer == null) {
return "";
} else {
return bufferToString(buffer, buffer.length, limitLength, DEFAULT_CHARSET);
}
}
/**
*
* @param buffer
* @param actualLength
* @param limitLength
* @param charset
* @return
*/
public static String bufferToString(byte[] buffer, int actualLength, int limitLength, Charset charset) {
if (actualLength > limitLength) {
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, limitLength);
return new StringBuilder(charset.decode(byteBuffer))
.append("n... (total ").append(actualLength).append(" bytes)")
.toString();
} else {
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, actualLength);
return charset.decode(byteBuffer).toString();
}
}
/**
* split and trim and normalized
* @param text
* @return
*/
public static List<String> splitAndTrim(String text, String regex) {
List<String> result = new ArrayList<String>();
if (isEmpty(text)) {
return result;
}
for (String s: text.split(regex)) {
if (StringUtils.isEmpty(s)) {
continue;
}
s = s.trim();
if (StringUtils.isEmpty(s)) {
continue;
}
result.add(s);
}
return result;
}
}
最后
以上就是会撒娇毛衣为你收集整理的Java常用 工具类的全部内容,希望文章能够帮你解决Java常用 工具类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复