50个JAVA常见代码大全

引言

Java 是一种广泛使用的编程语言,适用于多种应用场景,从企业级应用到移动应用开发。掌握一些常见的 Java 代码片段可以帮助开发者提高编码效率,解决常见问题。本文整理了50个常见的 Java 代码片段,涵盖了字符串处理、集合操作、文件操作、异常处理等多个方面,旨在为开发者提供实用的参考。

1. 字符串处理
  1. 字符串拼接

    String str1 = "Hello";
    String str2 = "World";
    String result = str1 + " " + str2;
  2. 字符串转大写

    String str = "hello";
    String upperCase = str.toUpperCase();
  3. 字符串转小写

    String str = "HELLO";
    String lowerCase = str.toLowerCase();
  4. 字符串截取

    String str = "Hello, World!";
    String subStr = str.substring(0, 5);
  5. 字符串分割

    String str = "Hello,World,Java";
    String[] parts = str.split(",");
  6. 字符串替换

    String str = "Hello, World!";
    String replaced = str.replace("World", "Java");
  7. 字符串去空格

    String str = " Hello, World! ";
    String trimmed = str.trim();
  8. 字符串长度

    String str = "Hello, World!";
    int length = str.length();
  9. 字符串包含

    String str = "Hello, World!";
    boolean contains = str.contains("World");
  10. 字符串比较

    String str1 = "Hello";
    String str2 = "hello";
    boolean equals = str1.equalsIgnoreCase(str2);
2. 集合操作
  1. 创建列表

    List list = new ArrayList<>();
    list.add("Apple");
    list.add("Banana");
  2. 遍历列表

    List list = Arrays.asList("Apple", "Banana", "Cherry");
    for (String item : list) {
        System.out.println(item);
    }
  3. 创建集合

    Set set = new HashSet<>();
    set.add("Apple");
    set.add("Banana");
  4. 遍历集合

    Set set = new HashSet<>(Arrays.asList("Apple", "Banana", "Cherry"));
    for (String item : set) {
        System.out.println(item);
    }
  5. 创建映射

    Map map = new HashMap<>();
    map.put("Apple", 1);
    map.put("Banana", 2);
  6. 遍历映射

    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());
    }
  7. 集合排序

    List list = Arrays.asList("Cherry", "Apple", "Banana");
    Collections.sort(list);
  8. 集合去重

    List list = Arrays.asList("Apple", "Banana", "Apple", "Cherry");
    Set uniqueSet = new HashSet<>(list);
  9. 集合转数组

    List list = Arrays.asList("Apple", "Banana", "Cherry");
    String[] array = list.toArray(new String[0]);
  10. 集合过滤

    List list = Arrays.asList("Apple", "Banana", "Cherry");
    List filteredList = list.stream()
                                    .filter(s -> s.startsWith("A"))
                                    .collect(Collectors.toList());
3. 文件操作
  1. 读取文件

    Path path = Paths.get("file.txt");
    List lines = Files.readAllLines(path);
  2. 写入文件

    Path path = Paths.get("file.txt");
    List lines = Arrays.asList("Hello", "World");
    Files.write(path, lines, StandardCharsets.UTF_8);
  3. 追加文件

    Path path = Paths.get("file.txt");
    List lines = Arrays.asList("Hello", "World");
    Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
  4. 删除文件

    Path path = Paths.get("file.txt");
    Files.delete(path);
  5. 创建目录

    Path path = Paths.get("newDir");
    Files.createDirectories(path);
  6. 遍历目录

    Path path = Paths.get("dir");
    Files.walk(path)
         .forEach(System.out::println);
  7. 复制文件

    Path source = Paths.get("source.txt");
    Path target = Paths.get("target.txt");
    Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
  8. 移动文件

    Path source = Paths.get("source.txt");
    Path target = Paths.get("target.txt");
    Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
  9. 检查文件是否存在

    Path path = Paths.get("file.txt");
    boolean exists = Files.exists(path);
  10. 获取文件大小

    Path path = Paths.get("file.txt");
    long size = Files.size(path);
4. 异常处理
  1. 捕获异常

    try {
        int result = 10 / 0;
    } catch (ArithmeticException e) {
        System.out.println("Division by zero error");
    }
  2. 抛出异常

    public void divide(int a, int b) throws ArithmeticException {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
  3. 自定义异常

    public class CustomException extends Exception {
        public CustomException(String message) {
            super(message);
        }
    }
  4. 多重捕获

    try {
        // Some code that may throw exceptions
    } catch (IOException | SQLException e) {
        System.out.println("Caught exception: " + e.getMessage());
    }
  5. 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");
    }
  6. 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. 线程与并发
  1. 创建线程

    Thread thread = new Thread(() -> {
        System.out.println("Thread is running");
    });
    thread.start();
  2. 同步方法

    public synchronized void synchronizedMethod() {
        // Synchronized code
    }
  3. 同步块

    Object lock = new Object();
    synchronized (lock) {
        // Synchronized code
    }
  4. 等待和通知

    Object lock = new Object();
    synchronized (lock) {
        try {
            lock.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized (lock) {
        lock.notify();
    }
  5. 线程池

    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();
  6. 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();
  7. 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");
  8. 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();
    }
  9. 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. 其他常用代码
  1. 日期和时间

    LocalDate date = LocalDate.now();
    LocalTime time = LocalTime.now();
    LocalDateTime dateTime = LocalDateTime.now();
  2. 格式化日期

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formattedDate = LocalDateTime.now().format(formatter);
  3. 解析日期

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse("2023-10-01 12:30:00", formatter);
  4. 随机数生成

    Random random = new Random();
    int randomNumber = random.nextInt(100);
  5. JSON处理

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", "John");
    jsonObject.put("age", 30);
    String jsonString = jsonObject.toString();
总结

以上是50个常见的 Java 代码片段,涵盖了字符串处理、集合操作、文件操作、异常处理、线程与并发以及其他常用操作。这些代码片段可以帮助开发者快速解决常见问题,提高开发效率。

上一篇:cpu怎么设置最佳性能(如何让CPU能发挥系统最大性能)
下一篇:windows7u盘重装系统(如何用u盘重装系统win7)