1. 獲取文件的byte[]一種最簡(jiǎn)單的方式
public static byte[] getBytesFromFile(String filePath) throws IOException {
Path path = Paths.get(filePath);
return Files.readAllBytes(path);
}
2. 使用Properties類讀寫properties文件
public static void getProp() throws Exception{
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream("D:\\test\\prop.properties");
properties.load(fileInputStream);
System.out.println("name="+properties.getProperty("name"));
}
public static void writeProp() throws Exception{
Properties properties = new Properties();
FileOutputStream fileOutputStream = new FileOutputStream("D:\\test\\new_prop.properties");
properties.setProperty("age","24");
properties.setProperty("name","liyubo");
properties.store(fileOutputStream,"Copyright (c) Liyubo Test");
}
3. 線程鎖定機(jī)制代碼片段
Lock lock = new ReentrantLock();
lock.lock();
try {
// update object state
}
finally {
lock.unlock();
}
4. 讀取maven的resource路徑下的文件
Demo1.class.getClassLoader().getResource("test/demo1.txt").getPath()
5. 典型的線程池代碼
//利用線程池技術(shù)模擬手機(jī)發(fā)送驗(yàn)證碼的場(chǎng)景
public class PhoneMsgSender {
//構(gòu)建一個(gè)線程池
private static final ExecutorService exeutor =
new ThreadPoolExecutor(
1,
Runtime.getRuntime().availableProcessors(),
60,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadFactory(){
public Thread newThread(Runnable r){
Thread t = new Thread(r,"PhoneMsgSender");
t.setDaemon(true);
return t;
}
}, new ThreadPoolExecutor.DiscardPolicy());
public void sendPhoneMsg(final String phoneNumber){
Runable task = new Runnable(){
public void run(){
doSend(phoneNumber);
}
};
//提交新任務(wù)
exeutor.submit(task);
}
//具體執(zhí)行發(fā)送信息任務(wù)
public void doSend(String phoneNumber){
System.out.println("Sending msg : " + phoneNumber);
//Todo
}
}
6. 一個(gè)含有泛型成員變量的類定義
@Data
public class Response<T> {
private Integer code;
private String msg;
private T data;
}
7. 文件轉(zhuǎn)properties處理
is = new FileInputStream(manager_path + "/conf/pme_manager.properties");
Properties pro = new Properties();
pro.load(is);
pro.getProperty("username_sys")
8. List<Integer>轉(zhuǎn)為int[]
int[] intArr = list.stream().mapToInt(Integer::intValue).toArray();
9. 變長(zhǎng)參數(shù)實(shí)例
public static int add(int ... data){
int sum = 0;
for(int x=0,length=data.length;x<length;x++){
sum += data[x];
}
return sum;
}
10. 獲取本機(jī)的網(wǎng)絡(luò)信息,主機(jī)遮婶,地址等
public static void main( String[] args ) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println("主機(jī)名:"+address.getHostName());
System.out.println("IP地址:"+address.getHostAddress());
}
11. 接收鍵盤輸入
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // 創(chuàng)建鍵盤錄入對(duì)象
System.out.println("請(qǐng)輸入第1個(gè)數(shù):");
int x = sc.nextInt();
System.out.println("請(qǐng)輸入第2個(gè)數(shù):");
int y = sc.nextInt();
int sum = x+y;
System.out.println("計(jì)算結(jié)果是:"+sum);
}
12. 修改文件屬組
UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService();
UserPrincipal userPrincipal = lookupService.lookupPrincipalByName("streaming");
GroupPrincipal group = lookupService.lookupPrincipalByGroupName("universe");
Files.setAttribute(Paths.get("/home/streaming/testfile"), "posix:group", group, LinkOption.NOFOLLOW_LINKS);
Files.setAttribute(Paths.get("/home/streaming/testfile"), "posix:owner", userPrincipal, LinkOption.NOFOLLOW_LINKS);
13. Map遍歷的效率提升
Map<String, String[]> paraMap = new HashMap<String, String[]>();
for( Entry<String, String[]> entry : paraMap.entrySet() )
{
String appFieldDefId = entry.getKey();
String[] values = entry.getValue();
}
14. 使用System.arraycopy()提升屬組復(fù)制效率
避免通過(guò)循環(huán)來(lái)迭代給兩個(gè)屬組進(jìn)行復(fù)制操作。
public class IRB {
void method () {
int[] array1 = new int [100];
for (int i = 0; i < array1.length; i++) {
array1 [i] = i;
}
int[] array2 = new int [100];
System.arraycopy(array1, 0, array2, 0, 100);
}
}
15. 判斷集合類等實(shí)例的相等
對(duì)于基本類型我們用==判斷就可以君躺,如果是String類型我們使用equals旦事,這個(gè)是很基礎(chǔ)的知識(shí)了。那么我們?cè)趺磁袛鄡蓚€(gè)對(duì)象是否相等呢?
對(duì)于集合類的對(duì)象卷仑,我們可以遍歷對(duì)象中的每個(gè)數(shù)據(jù),逐一判斷是否相等麸折,這是簡(jiǎn)單粗暴的方式锡凝。那么如果我們判斷兩個(gè)class是否相等該怎么做呢?答案是用hashcode垢啼。
if(obj1.toString().hashCode()==obj2.toString().hashCode())
這里的重點(diǎn)是你比較的對(duì)象必須先轉(zhuǎn)成String串窜锯,然后比較String串的hashcode。因?yàn)橹苯颖容^對(duì)象的hashcode那是肯定不一樣的芭析。
16. Array轉(zhuǎn)ArrayList的正確方法
Arrays.asList()
會(huì)返回一個(gè)ArrayList锚扎,但是要特別注意,這個(gè)ArrayList是Arrays類的靜態(tài)內(nèi)部類放刨,并不是java.util.ArrayList類工秩。java.util.Arrays.ArrayList類實(shí)現(xiàn)了set(), get()进统,contains()方法助币,但是并沒(méi)有實(shí)現(xiàn)增加元素的方法(事實(shí)上是可以調(diào)用add方法,但是沒(méi)有具體實(shí)現(xiàn)螟碎,僅僅拋出UnsupportedOperationException異常)眉菱,因此它的大小也是固定不變的。為了創(chuàng)建一個(gè)真正的java.util.ArrayList掉分,你應(yīng)該這樣做:
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));
17. 判斷一個(gè)數(shù)組是否包含某個(gè)值
Arrays.asList(arr).contains(targetValue);
18. 循環(huán)過(guò)程中刪除指定元素
由于List或者Set中的元素本質(zhì)上是存在index的俭缓,所有當(dāng)在增強(qiáng)for循環(huán)中進(jìn)行刪除的時(shí)候,會(huì)導(dǎo)致異常:java.util.ConcurrentModificaionExcepton
酥郭。此時(shí)使用普通的for循環(huán)是可以的华坦。注意:不要使用增強(qiáng)for循環(huán)。
Iterator<String> it = list.iterator();
while(it.hasNext()){
String x = it.next();
if(x.equals("del")){
it.remove();
}
}
另一種簡(jiǎn)單有效的循環(huán)過(guò)程中刪除指定元素的方法
依賴JDK8中的lamda表達(dá)式
String[] arrays = {"1", "2", "3"};
List<String> list = new ArrayList<String>(Arrays.asList(arrays));
list.removeIf(str -> str.equals("1"));
19. 多個(gè)List合并成同一個(gè)
List<Integer> a = Arrays.asList(1, 2, 3);
List<Integer> b = Arrays.asList(4, 5, 6);
List<List<Integer>> collect = Stream.of(a, b).collect(Collectors.toList());
20. 對(duì)list中的元素進(jìn)行排序
List<String> list = Arrays.asList("c", "e", "a", "d", "b");
list.stream().sorted((s1, s2) -> s1.compareTo(s2)).forEach(System.out::println);
21. Java中的除法取整
向上取整是一個(gè)常用的算法技巧不从。大部分編程語(yǔ)言中惜姐,如果你想計(jì)算 M 除以 N,M / N 會(huì)向下取整,你想向上取整的話歹袁,可以改成 (M+(N-1)) / N