引言
Java 是一种广泛使用的编程语言,适用于多种应用场景,从企业级应用到移动应用开发。掌握一些常见的 Java 代码片段可以帮助开发者提高编码效率,解决常见问题。本文整理了50个常见的 Java 代码片段,涵盖了字符串处理、集合操作、文件操作、异常处理等多个方面,旨在为开发者提供实用的参考。
1. 字符串处理
-
字符串拼接
String str1 = "Hello"; String str2 = "World"; String result = str1 + " " + str2;
-
字符串转大写
String str = "hello"; String upperCase = str.toUpperCase();
-
字符串转小写
String str = "HELLO"; String lowerCase = str.toLowerCase();
-
字符串截取
String str = "Hello, World!"; String subStr = str.substring(0, 5);
-
字符串分割
String str = "Hello,World,Java"; String[] parts = str.split(",");
-
字符串替换
String str = "Hello, World!"; String replaced = str.replace("World", "Java");
-
字符串去空格
String str = " Hello, World! "; String trimmed = str.trim();
-
字符串长度
String str = "Hello, World!"; int length = str.length();
-
字符串包含
String str = "Hello, World!"; boolean contains = str.contains("World");
-
字符串比较
String str1 = "Hello"; String str2 = "hello"; boolean equals = str1.equalsIgnoreCase(str2);
2. 集合操作
-
创建列表
List
list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); -
遍历列表
List
list = Arrays.asList("Apple", "Banana", "Cherry"); for (String item : list) { System.out.println(item); } -
创建集合
Set
set = new HashSet<>(); set.add("Apple"); set.add("Banana"); -
遍历集合
Set
set = new HashSet<>(Arrays.asList("Apple", "Banana", "Cherry")); for (String item : set) { System.out.println(item); } -
创建映射
Map
map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); -
遍历映射
Map
map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } -
集合排序
List
list = Arrays.asList("Cherry", "Apple", "Banana"); Collections.sort(list); -
集合去重
List
list = Arrays.asList("Apple", "Banana", "Apple", "Cherry"); Set uniqueSet = new HashSet<>(list); -
集合转数组
List
list = Arrays.asList("Apple", "Banana", "Cherry"); String[] array = list.toArray(new String[0]); -
集合过滤
List
list = Arrays.asList("Apple", "Banana", "Cherry"); List filteredList = list.stream() .filter(s -> s.startsWith("A")) .collect(Collectors.toList());
3. 文件操作
-
读取文件
Path path = Paths.get("file.txt"); List
lines = Files.readAllLines(path); -
写入文件
Path path = Paths.get("file.txt"); List
lines = Arrays.asList("Hello", "World"); Files.write(path, lines, StandardCharsets.UTF_8); -
追加文件
Path path = Paths.get("file.txt"); List
lines = Arrays.asList("Hello", "World"); Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND); -
删除文件
Path path = Paths.get("file.txt"); Files.delete(path);
-
创建目录
Path path = Paths.get("newDir"); Files.createDirectories(path);
-
遍历目录
Path path = Paths.get("dir"); Files.walk(path) .forEach(System.out::println);
-
复制文件
Path source = Paths.get("source.txt"); Path target = Paths.get("target.txt"); Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
-
移动文件
Path source = Paths.get("source.txt"); Path target = Paths.get("target.txt"); Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
-
检查文件是否存在
Path path = Paths.get("file.txt"); boolean exists = Files.exists(path);
-
获取文件大小
Path path = Paths.get("file.txt"); long size = Files.size(path);
4. 异常处理
-
捕获异常
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Division by zero error"); }
-
抛出异常
public void divide(int a, int b) throws ArithmeticException { if (b == 0) { throw new ArithmeticException("Division by zero"); } return a / b; }
-
自定义异常
public class CustomException extends Exception { public CustomException(String message) { super(message); } }
-
多重捕获
try { // Some code that may throw exceptions } catch (IOException | SQLException e) { System.out.println("Caught exception: " + e.getMessage()); }
-
finally块
try { // Some code that may throw exceptions } catch (IOException e) { System.out.println("Caught exception: " + e.getMessage()); } finally { System.out.println("Finally block executed"); }
-
try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println("Error reading file: " + e.getMessage()); }
5. 线程与并发
-
创建线程
Thread thread = new Thread(() -> { System.out.println("Thread is running"); }); thread.start();
-
同步方法
public synchronized void synchronizedMethod() { // Synchronized code }
-
同步块
Object lock = new Object(); synchronized (lock) { // Synchronized code }
-
等待和通知
Object lock = new Object(); synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized (lock) { lock.notify(); }
-
线程池
ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < 10; i++) { executor.submit(() -> { System.out.println("Task executed by " + Thread.currentThread().getName()); }); } executor.shutdown();
-
Future和Callable
ExecutorService executor = Executors.newSingleThreadExecutor(); Future
future = executor.submit(() -> { return 10; }); try { int result = future.get(); System.out.println("Result: " + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executor.shutdown(); -
CountDownLatch
CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println("Thread " + Thread.currentThread().getName() + " is running"); latch.countDown(); }).start(); } latch.await(); System.out.println("All threads have finished");
-
CyclicBarrier
CyclicBarrier barrier = new CyclicBarrier(3, () -> { System.out.println("All parties have arrived at the barrier"); }); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println("Thread " + Thread.currentThread().getName() + " is waiting"); try { barrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }).start(); }
-
Semaphore
Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 5; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println("Thread " + Thread.currentThread().getName() + " acquired permit"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); System.out.println("Thread " + Thread.currentThread().getName() + " released permit"); } }).start(); }
6. 其他常用代码
-
日期和时间
LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dateTime = LocalDateTime.now();
-
格式化日期
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = LocalDateTime.now().format(formatter);
-
解析日期
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse("2023-10-01 12:30:00", formatter);
-
随机数生成
Random random = new Random(); int randomNumber = random.nextInt(100);
-
JSON处理
JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 30); String jsonString = jsonObject.toString();
总结
以上是50个常见的 Java 代码片段,涵盖了字符串处理、集合操作、文件操作、异常处理、线程与并发以及其他常用操作。这些代码片段可以帮助开发者快速解决常见问题,提高开发效率。