JAVA基礎庫的使用點滴,java基礎點滴
Idea中雙擊SHIFT可以搜尋[Eclipse中也有],這個很重要,可以找到當前的項目中可以引擎的已有的類,不要再次自己發明輪子
各種Util先在基礎庫和開源庫中找
Base64編碼
guava:com.google.common.io.BaseEncoding
commons-codec:org.apache.commons.codec.binary.Base64
各種摘要等演算法都有了
[WARNING] /opt/work/2014/work/centos2017/webman/webman/src/main/java/cn/csbit/util/License.java:[370,41] sun.misc.BASE64Encoder是內部專用 API, 可能會在未來發行版中刪除
[WARNING] /opt/work/2014/work/centos2017/webman/webman/src/main/java/cn/csbit/core/report/vo/ReportVo.java
日期
commons-lang
org.apache.commons.lang.SerializationUtils
org.apache.commons.lang.time
DateFormatUtils DateUtils
cn.csbit.core.util.DateUtil
字串處理
org.apache.commons.codec.binary
org.apache.commons.lang StringUtils
Files
JDK新的版本才加的方便檔案操作的類已經都有了
commons-io
org.apache.commons.io FilenameUtils 檔案名稱的各種處理
FileSystemUtils 磁碟空間的狀況
數字轉換
Ints Longs Shorts UnsignedInts
com.google.common.primitives
@GwtIncompatible("doesn\'t work")
public static byte[] toByteArray(int value) {
return new byte[]{(byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value};
}
@GwtIncompatible("doesn\'t work")
public static int fromByteArray(byte[] bytes) {
Preconditions.checkArgument(bytes.length >= 4, "array too small: %s < %s", new Object[]{Integer.valueOf(bytes.length), Integer.valueOf(4)});
return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]);
}
public static byte[] shortToBytes(short number) {
int temp = number;
byte[] b = new byte[2];
for (int i = 0; i < b.length; i++) {
b[i] = new Integer(temp & 0xff).byteValue();// 將最低位儲存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}
public static byte[] toByteArray(int value) {
byte[] array = new byte[4];
for (int i = 0; i < 4; i++) {
array[i] = (byte) ((value >> (8 * i)) & 0XFF);
}
return array;
}
NumberUtil common-lang也有類似
IP地址
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteBuffer.LITTEN_ENDIAN);
b.putIn(100);
b.array();//可以擷取位元組數組
com.google.common.net.InetAddresses