Java工具类案例

wen java案例 3

本文目录导读:

Java工具类案例

  1. 字符串工具类
  2. 日期工具类
  3. HTTP请求工具类
  4. 文件工具类
  5. 使用示例

我来为您提供几个实用的Java工具类案例,涵盖常见开发场景:

字符串工具类

import java.util.regex.Pattern;
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public class StringUtils {
    // 判断字符串是否为空
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    // 判断字符串是否不为空
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }
    // 截取字符串
    public static String substring(String str, int start, int end) {
        if (str == null) return "";
        if (end < 0) end = str.length() + end;
        if (start < 0) start = str.length() + start;
        if (end > str.length()) end = str.length();
        if (start < 0) start = 0;
        if (start > end) return "";
        return str.substring(start, end);
    }
    // 首字母大写
    public static String capitalizeFirstLetter(String str) {
        if (isEmpty(str)) return str;
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }
    // 下划线转驼峰
    public static String underlineToCamel(String underlineStr) {
        if (isEmpty(underlineStr)) return underlineStr;
        String[] parts = underlineStr.split("_");
        StringBuilder result = new StringBuilder(parts[0]);
        for (int i = 1; i < parts.length; i++) {
            result.append(capitalizeFirstLetter(parts[i]));
        }
        return result.toString();
    }
    // 驼峰转下划线
    public static String camelToUnderline(String camelStr) {
        if (isEmpty(camelStr)) return camelStr;
        return camelStr.replaceAll("([A-Z])", "_$1").toLowerCase();
    }
    // 字符串重复
    public static String repeat(String str, int times) {
        if (str == null || times <= 0) return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append(str);
        }
        return sb.toString();
    }
    // 去除字符串中的特殊字符
    public static String removeSpecialChars(String str) {
        if (isEmpty(str)) return str;
        return str.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
    }
    // MD5加密
    public static String md5(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                result.append(String.format("%02x", b));
            }
            return result.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
}

日期工具类

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
public class DateUtils {
    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
    // 获取当前时间字符串
    public static String now() {
        return format(LocalDateTime.now());
    }
    // 格式化日期
    public static String format(LocalDateTime dateTime) {
        return format(dateTime, DEFAULT_FORMAT);
    }
    public static String format(LocalDateTime dateTime, String pattern) {
        if (dateTime == null) return "";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return dateTime.format(formatter);
    }
    // 解析日期字符串
    public static LocalDateTime parse(String dateStr) {
        return parse(dateStr, DEFAULT_FORMAT);
    }
    public static LocalDateTime parse(String dateStr, String pattern) {
        if (isEmpty(dateStr)) return null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(dateStr, formatter);
    }
    // 日期加减天
    public static LocalDateTime addDays(LocalDateTime date, long days) {
        return date.plusDays(days);
    }
    // 日期加减小时
    public static LocalDateTime addHours(LocalDateTime date, long hours) {
        return date.plusHours(hours);
    }
    // 计算两个日期之间的天数
    public static long daysBetween(LocalDateTime start, LocalDateTime end) {
        return ChronoUnit.DAYS.between(start, end);
    }
    // 获取当月第一天
    public static LocalDate getFirstDayOfMonth(LocalDate date) {
        return date.withDayOfMonth(1);
    }
    // 获取当月最后一天
    public static LocalDate getLastDayOfMonth(LocalDate date) {
        return date.withDayOfMonth(date.lengthOfMonth());
    }
    // 判断是否为闰年
    public static boolean isLeapYear(int year) {
        return Year.isLeap(year);
    }
    // LocalDateTime转Date
    public static Date toDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
}

HTTP请求工具类

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class HttpUtils {
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 5000;
    // GET请求
    public static String get(String urlStr) {
        return get(urlStr, null);
    }
    public static String get(String urlStr, Map<String, String> headers) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return readResponse(connection);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("GET请求失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    // POST请求
    public static String post(String urlStr, String jsonBody) {
        return post(urlStr, jsonBody, null);
    }
    public static String post(String urlStr, String jsonBody, Map<String, String> headers) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 写入请求体
            if (jsonBody != null && !jsonBody.isEmpty()) {
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return readResponse(connection);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException("POST请求失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    // 读取响应
    private static String readResponse(HttpURLConnection connection) throws Exception {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }
}

文件工具类

import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;
public class FileUtils {
    // 创建目录
    public static void createDirectory(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }
    // 创建文件
    public static void createFile(String filePath) throws IOException {
        File file = new File(filePath);
        File parent = file.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        file.createNewFile();
    }
    // 写入文件
    public static void writeFile(String filePath, String content) throws IOException {
        Files.write(Paths.get(filePath), content.getBytes(StandardCharsets.UTF_8));
    }
    // 追加写入
    public static void appendToFile(String filePath, String content) throws IOException {
        Files.write(Paths.get(filePath), content.getBytes(StandardCharsets.UTF_8), 
                   StandardOpenOption.APPEND, StandardOpenOption.CREATE);
    }
    // 读取文件内容
    public static String readFile(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    }
    // 读取所有行
    public static List<String> readLines(String filePath) throws IOException {
        return Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
    }
    // 复制文件
    public static void copyFile(String sourcePath, String destPath) throws IOException {
        Files.copy(Paths.get(sourcePath), Paths.get(destPath), 
                  StandardCopyOption.REPLACE_EXISTING);
    }
    // 移动文件
    public static void moveFile(String sourcePath, String destPath) throws IOException {
        Files.move(Paths.get(sourcePath), Paths.get(destPath), 
                  StandardCopyOption.REPLACE_EXISTING);
    }
    // 删除文件
    public static void deleteFile(String filePath) throws IOException {
        Files.delete(Paths.get(filePath));
    }
    // 递归删除目录
    public static void deleteDirectory(File directory) {
        if (directory == null || !directory.exists()) return;
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteDirectory(file);
                }
            }
        }
        directory.delete();
    }
    // 获取文件大小(字节)
    public static long getFileSize(String filePath) throws IOException {
        return Files.size(Paths.get(filePath));
    }
    // 遍历目录下所有文件
    public static List<File> listFiles(File directory) {
        List<File> files = new ArrayList<>();
        if (!directory.isDirectory()) return files;
        File[] items = directory.listFiles();
        if (items != null) {
            for (File item : items) {
                if (item.isFile()) {
                    files.add(item);
                } else {
                    files.addAll(listFiles(item));
                }
            }
        }
        return files;
    }
}

使用示例

public class UtilsDemo {
    public static void main(String[] args) {
        // 字符串工具类
        System.out.println("字符串工具类测试:");
        System.out.println("isEmpty(\"\") = " + StringUtils.isEmpty(""));
        System.out.println("capitalizeFirstLetter(\"hello\") = " + 
                          StringUtils.capitalizeFirstLetter("hello"));
        System.out.println("underlineToCamel(\"user_name\") = " + 
                          StringUtils.underlineToCamel("user_name"));
        System.out.println("camelToUnderline(\"userName\") = " + 
                          StringUtils.camelToUnderline("userName"));
        System.out.println("md5(\"123456\") = " + StringUtils.md5("123456"));
        // 日期工具类
        System.out.println("\n日期工具类测试:");
        System.out.println("当前时间:" + DateUtils.now());
        LocalDateTime tomorrow = DateUtils.addDays(LocalDateTime.now(), 1);
        System.out.println("明天:" + DateUtils.format(tomorrow));
        System.out.println("是否为闰年:2024 = " + DateUtils.isLeapYear(2024));
        // 文件工具类
        System.out.println("\n文件工具类测试:");
        try {
            String filePath = "test.txt";
            FileUtils.writeFile(filePath, "Hello, World!");
            String content = FileUtils.readFile(filePath);
            System.out.println("文件内容:" + content);
            FileUtils.deleteFile(filePath);
            System.out.println("文件已删除");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这些工具类都是实际开发中常用的功能,您可以根据需要进行修改和扩展,每个工具类都设计得简单实用,直接复制即可使用。

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