java执行片段_Java代码片段库

1. 获取文件的byte[]一种最简单的方式

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. 线程锁定机制代码片段

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. 典型的线程池代码

//利用线程池技术模拟手机发送验证码的场景

public class PhoneMsgSender {

//构建一个线程池

private static final ExecutorService exeutor =

new ThreadPoolExecutor(

1,

Runtime.getRuntime().availableProcessors(),

60,

TimeUnit.SECONDS,

new SynchronousQueue(),

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);

}

};

//提交新任务

exeutor.submit(task);

}

//具体执行发送信息任务

public void doSend(String phoneNumber){

System.out.println("Sending msg : " + phoneNumber);

//Todo

}

}

6. 一个含有泛型成员变量的类定义

@Data

public class Response {

private Integer code;

private String msg;

private T data;

}

7. 文件转properties处理

is = new FileInputStream(manager_path + "/conf/pme_manager.properties");

Properties pro = new Properties();

pro.load(is);

pro.getProperty("username_sys")

8. List转为int[]

int[] intArr = list.stream().mapToInt(Integer::intValue).toArray();

9. 变长参数实例

public static int add(int ... data){

int sum = 0;

for(int x=0,length=data.length;x

sum += data[x];

}

return sum;

}

10. 获取本机的网络信息,主机,地址等

public static void main( String[] args ) throws UnknownHostException {

InetAddress address = InetAddress.getLocalHost();

System.out.println("主机名:"+address.getHostName());

System.out.println("IP地址:"+address.getHostAddress());

}

11. 接收键盘输入

public static void main(String[] args) {

Scanner sc = new Scanner(System.in); // 创建键盘录入对象

System.out.println("请输入第1个数:");

int x = sc.nextInt();

System.out.println("请输入第2个数:");

int y = sc.nextInt();

int sum = x+y;

System.out.println("计算结果是:"+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 paraMap = new HashMap();

for( Entry entry : paraMap.entrySet() )

{

String appFieldDefId = entry.getKey();

String[] values = entry.getValue();

}

14. 使用System.arraycopy()提升属组复制效率

避免通过循环来迭代给两个属组进行复制操作。

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. 判断集合类等实例的相等

对于基本类型我们用==判断就可以,如果是String类型我们使用equals,这个是很基础的知识了。那么我们怎么判断两个对象是否相等呢?

对于集合类的对象,我们可以遍历对象中的每个数据,逐一判断是否相等,这是简单粗暴的方式。那么如果我们判断两个class是否相等该怎么做呢?答案是用hashcode。

if(obj1.toString().hashCode()==obj2.toString().hashCode())

这里的重点是你比较的对象必须先转成String串,然后比较String串的hashcode。因为直接比较对象的hashcode那是肯定不一样的。

16. Array转ArrayList的正确方法

Arrays.asList()会返回一个ArrayList,但是要特别注意,这个ArrayList是Arrays类的静态内部类,并不是java.util.ArrayList类。java.util.Arrays.ArrayList类实现了set(), get(),contains()方法,但是并没有实现增加元素的方法(事实上是可以调用add方法,但是没有具体实现,仅仅抛出UnsupportedOperationException异常),因此它的大小也是固定不变的。为了创建一个真正的java.util.ArrayList,你应该这样做:

ArrayList arrayList = new ArrayList(Arrays.asList(arr));

17. 判断一个数组是否包含某个值

Arrays.asList(arr).contains(targetValue);

18. 循环过程中删除指定元素

由于List或者Set中的元素本质上是存在index的,所有当在增强for循环中进行删除的时候,会导致异常:java.util.ConcurrentModificaionExcepton。此时使用普通的for循环是可以的。注意:不要使用增强for循环。

Iterator it = list.iterator();

while(it.hasNext()){

String x = it.next();

if(x.equals("del")){

it.remove();

}

}

另一种简单有效的循环过程中删除指定元素的方法

依赖JDK8中的lamda表达式

String[] arrays = {"1", "2", "3"};

List list = new ArrayList(Arrays.asList(arrays));

list.removeIf(str -> str.equals("1"));

19. 多个List合并成同一个

List a = Arrays.asList(1, 2, 3);

List b = Arrays.asList(4, 5, 6);

List> collect = Stream.of(a, b).collect(Collectors.toList());

20. 对list中的元素进行排序

List list = Arrays.asList("c", "e", "a", "d", "b");

list.stream().sorted((s1, s2) -> s1.compareTo(s2)).forEach(System.out::println);

21. Java中的除法取整

向上取整是一个常用的算法技巧。大部分编程语言中,如果你想计算 M 除以 N,M / N 会向下取整,你想向上取整的话,可以改成 (M+(N-1)) / N

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值