Java工具调用案例

wen java案例 2

本文目录导读:

Java工具调用案例

  1. 调用系统命令工具
  2. 调用Java内部工具类
  3. 调用第三方工具库
  4. 自定义工具类
  5. 实际业务场景:文件处理工具
  6. 关键工具调用模式总结

调用系统命令工具

import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SystemCommandExample {
    public static void main(String[] args) {
        try {
            // 示例1: 调用ping命令
            System.out.println("=== 执行ping命令 ===");
            ProcessBuilder pb = new ProcessBuilder("ping", "-c", "4", "www.baidu.com");
            Process process = pb.start();
            // 读取命令输出
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待命令执行完成
            int exitCode = process.waitFor();
            System.out.println("退出代码: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

调用Java内部工具类

import java.util.*;
import java.util.stream.*;
public class JavaToolsExample {
    public static void main(String[] args) {
        // 示例1: 使用Collections工具类
        System.out.println("=== Collections工具类 ===");
        List<String> list = new ArrayList<>(Arrays.asList("c", "a", "b"));
        Collections.sort(list);
        System.out.println("排序后: " + list);
        // 示例2: 使用Arrays工具类
        System.out.println("\n=== Arrays工具类 ===");
        int[] numbers = {5, 2, 8, 1, 9};
        Arrays.sort(numbers);
        System.out.println("排序数组: " + Arrays.toString(numbers));
        // 示例3: 使用Stream API
        System.out.println("\n=== Stream API ===");
        List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6);
        List<Integer> evenNumbers = nums.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        System.out.println("偶数: " + evenNumbers);
        // 示例4: 使用Optional避免空指针
        System.out.println("\n=== Optional工具类 ===");
        String str = null;
        String result = Optional.ofNullable(str)
            .orElse("默认值");
        System.out.println("处理空值: " + result);
    }
}

调用第三方工具库

// 需要添加依赖:com.google.guava:guava:31.1-jre
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class GuavaToolsExample {
    public static void main(String[] args) {
        // 示例1: 字符串连接
        System.out.println("=== Guava Joiner ===");
        List<String> words = Arrays.asList("Hello", "World", "Java", "Guava");
        String joined = Joiner.on(", ").join(words);
        System.out.println("连接字符串: " + joined);
        // 示例2: 字符串分割
        System.out.println("\n=== Guava Splitter ===");
        String csv = "apple,banana,,orange,grape";
        Iterable<String> split = Splitter.on(",")
            .trimResults()
            .omitEmptyStrings()
            .split(csv);
        System.out.println("分割结果: " + Lists.newArrayList(split));
        // 示例3: 集合工具
        System.out.println("\n=== Guava Lists ===");
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
        List<List<Integer>> partitions = Lists.partition(numbers, 3);
        System.out.println("分组结果: " + partitions);
    }
}

自定义工具类

public class CustomTools {
    // 字符串工具
    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }
    public static String capitalize(String str) {
        if (isEmpty(str)) return str;
        return str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
    }
    // 数字工具
    public static int parseInt(String str, int defaultValue) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    // 日期工具
    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }
    public static void main(String[] args) {
        // 使用自定义工具类
        System.out.println("=== 自定义工具类使用 ===");
        System.out.println("空字符串检查: " + isEmpty("  "));
        System.out.println("首字母大写: " + capitalize("hello world"));
        System.out.println("安全转换数字: " + parseInt("123", 0));
        Date now = new Date();
        System.out.println("格式化日期: " + formatDate(now, "yyyy-MM-dd HH:mm:ss"));
    }
}

实际业务场景:文件处理工具

import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;
public class FileProcessorExample {
    // 读取文件内容
    public static String readFile(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)));
    }
    // 写入文件
    public static void writeFile(String filePath, String content) throws IOException {
        Files.write(Paths.get(filePath), content.getBytes());
    }
    // 复制文件
    public static void copyFile(String source, String dest) throws IOException {
        Files.copy(Paths.get(source), Paths.get(dest), StandardCopyOption.REPLACE_EXISTING);
    }
    // 读取CSV文件
    public static List<String[]> readCSV(String filePath) throws IOException {
        return Files.lines(Paths.get(filePath))
            .map(line -> line.split(","))
            .collect(Collectors.toList());
    }
    public static void main(String[] args) {
        try {
            // 创建示例文件
            String content = "name,age,city\nAlice,25,Beijing\nBob,30,Shanghai";
            String filePath = "example.csv";
            // 写入文件
            writeFile(filePath, content);
            System.out.println("文件已创建: " + filePath);
            // 读取文件
            String fileContent = readFile(filePath);
            System.out.println("文件内容:\n" + fileContent);
            // 解析CSV
            List<String[]> records = readCSV(filePath);
            System.out.println("\nCSV记录:");
            for (String[] record : records) {
                System.out.println(Arrays.toString(record));
            }
            // 清理
            Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            System.err.println("文件处理错误: " + e.getMessage());
        }
    }
}

关键工具调用模式总结

工具类型 示例 适用场景
系统命令 Runtime, ProcessBuilder 系统管理、命令执行
Java内置工具 Collections, Arrays, Stream 数据处理、集合操作
第三方库 Guava, Apache Commons 增强功能、简化开发
自定义工具 业务工具类 特定业务逻辑封装

这些示例展示了Java中不同类型的工具调用方法,你可以根据具体需求选择合适的工具调用模式。

抱歉,评论功能暂时关闭!