Java-常用工具类:Math、Random、日期、System、File、Properties和枚举

1、Math 类(数学计算)

提供执行基本数学运算的静态方法。不需要创建对象,直接通过类名调用。

public class Utility{
    public static void main(String[] args) {
        Math.abs(-5); //求绝对值,5
        Math.ceil(3.2);//向上取整,4
        Math.floor(3.8);//向下取整,3
        Math.round(3.5);//四舍五入,4
        Math.max(3, 5);//求最大值,5
        Math.sqrt(9);//求平方根,3
        Math.random();//生成随机数 [0.0, 1.0),包含0、不包含1

    }
}

2、Random 类(随机数生成)

用于生成各种类型的伪随机数。相比Math.random(),它更灵活,可以控制随机数范围和类型。

import java.util.Random;

public class Utility{
    public static void main(String[] args) {
        //new Random(种子值):默认种子是时间,种子相同,生成的随机数序列相同
        Random random = new Random(); 
        random.nextInt(100); //生成 [0, bound) 的随机整数
        random.nextInt(); //生成所有可能int值范围的随机整数
        random.nextDouble(); //生成 [0.0, 1.0) 的随机小数
        random.nextBoolean(); //生成 true 或 false
        random.nextLong(); //生成随机长整数
    }
}

3、Scanner 类(用户输入)

用于从控制台(键盘)或文件中读取基本类型和字符串的输入。

import java.util.Scanner;

public class Utility{
    public static void main(String[] args) {
        Scanner scanner = null; // 1. 在外部声明并初始化为 null
        try {
            scanner = new Scanner(System.in);
            int age = scanner.nextInt(); //读取下一个整数
            //nextLine()开始读取到回车会直接结束读取:nextInt()后调用一次scanner.nextLine()来处理回车,处理后再调用nextLine()
            scanner.nextLine(); //处理回车
            String name = scanner.nextLine(); //读取当前行的所有内容(以回车结束),返回字符串
            String word = scanner.next(); //读取下一个以空格/回车分隔的单词,返回字符串

        } catch (Exception e ){
            e.printStackTrace();

        } finally{
            scanner.close();
        }
    }
}

4、日期时间(Date & LocalDateTime)

处理日期、时间、时间戳。Java 8 引入了全新的 java.time 包,强烈建议使用新API,旧版 Date 和 Calendar 存在设计缺陷。

  • 旧版(了解即可):java.util.Date 和 java.util.Calendar,很多方法已废弃,线程不安全。
  • 新版(重点掌握):java.time 包下的类,线程安全,设计清晰。
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;


public class Utility{
    public static void main(String[] args) {
        LocalDate.now(); //日期,2026-08-10
        LocalTime.now(); //时间,15:30:45.123
        LocalDateTime.now(); //日期+时间,2026-08-10T15:30:45.123

        //格式化日期+时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted = now.format(formatter);  //格式化
        System.out.println(formatted);

    }
}

5、System类(系统级操作)

public class SystemDemo {
    public static void main(String[] args) {
        // 标准输出
        System.out.println("Hello");

        // 标准错误输出(打印异常信息)
        System.err.println("错误信息");
        
        // 1. 计时,currentTimeMillis()获取当前时间戳(毫秒,常用于计算耗时)
        long start = System.currentTimeMillis();
        // ... 执行某些操作 ...
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start) + "ms");

        // 2. getProperty()用于获取系统属性
        System.out.println("Java版本:" + System.getProperty("java.version"));
        System.out.println("操作系统:" + System.getProperty("os.name"));
        System.out.println("工作目录:" + System.getProperty("user.dir"));
    }
}

6、File类(文件和目录的“名片”)

File代表文件或目录的路径名,并不操作文件内容。读写文件内容要用I/O流。

import java.io.File;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) {
        File file = new File("test.txt");
        
        // 判断文件是否存在
        if (!file.exists()) {
            try {
                file.createNewFile(); // 创建新文件
                System.out.println("文件已创建");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        System.out.println("文件名:" + file.getName());
        System.out.println("绝对路径:" + file.getAbsolutePath());
        System.out.println("文件大小:" + file.length() + " 字节");
        
        // 遍历目录
        File dir = new File(".");
        for (File f : dir.listFiles()) { //listFiles()列出目录下的所有子文件和目录
            System.out.println(f.getName());
        }
    }
}

7、Properties类(轻量级配置文件读写)

用于加载和存储.properties格式的配置文件(键值对,通常用于保存配置参数)。

/* config.properties 文件内容
username=admin
password=123456
url=jdbc:mysql://localhost:3306/test
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {
    public static void main(String[] args) {
        Properties props = new Properties();

        // 1. 加载配置文件
        try (FileInputStream fis = new FileInputStream("config.properties")) {
            props.load(fis); // 从输入流中读取键值对列表
            // 读取配置
            String username = props.getProperty("username");
            String password = props.getProperty("password");
            String url = props.getProperty("url");
            System.out.println("用户名:" + username);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 2. 修改并保存配置
        props.setProperty("timeout", "5000"); // 新增键值对
        try (FileOutputStream fos = new FileOutputStream("config.properties")) {
            props.store(fos, "Updated config"); //存储新键值对
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 8、枚举

枚举是一种特殊的类,用来定义一组固定的常量。比如:季节(春、夏、秋、冬)、状态(成功、失败、进行中)、星期(一至日)。

每个枚举常量可以有自己的属性和行为,非常方便。

enum Season {
    // 枚举常量列表,必须在第一行。自动调用构造方法创建实例
    SPRING("春天", "春暖花开"),
    SUMMER("夏天", "夏日炎炎");

    // 成员变量
    private final String chineseName;
    private final String description;

    // 构造方法:必须是 private(默认也是 private)
    // 自动调用构造方法创建枚举常量成员
    Season(String chineseName, String description) {
        this.chineseName = chineseName;
        this.description = description;
    }

    // 公共方法,获取中文名称
    public String getChineseName() {
        return chineseName;
    }

    // 公共方法,获取描述
    public String getDescription() {
        return description;
    }

    // 自定义方法:根据季节推荐活动
    public String recommendActivity() {
        switch (this) {
            case SPRING: return "放风筝";
            case SUMMER: return "游泳";
            default: return "休息";
        }
    }
}

public class EnumDemo {
    public static void main(String[] args) {

        // 1. 遍历所有枚举值,values()返回包含所有枚举常量的数组
        for (Season s : Season.values()) {
            // name()返回枚举常量的名
            // ordinal()返回枚举常量的顺序
            System.out.println(s.name() + " - " + s.ordinal());
        }

        // valueOf(String)将字符串常量转换为对应的枚举常量
        // 字符串必须与枚举常量名称完全一致(包括大小写),否则抛 IllegalArgumentException
        Season spring = Season.valueOf("SPRING");
        System.out.println(spring); // 输出 SPRING

        // 使用方法
        Season season = Season.SPRING;
        System.out.println(season.getChineseName()); // 输出:春天
        System.out.println(season.recommendActivity()); // 输出:放风筝
    }
}

 9、Fastjson2 

序列化:Java Object转换为JSON数据

import java.util.Date;
import com.alibaba.fastjson2.annotation.JSONField;

public class User {
    @JSONField(name = "user_name") // 指定序列化后 JSON 中的字段名
    private String name;
    private int age;
    @JSONField(format = "yyyy-MM-dd HH:mm:ss") // 指定日期格式
    private Date createTime;

    // 无参构造(反序列化需要)
    public User() {}
    
    // 有参构造
    public User(String name, int age, Date createTime) {
        this.name = name;
        this.age = age;
        this.createTime = createTime;
    }

    // getter/setter 略...
}
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import java.util.*;

public class FastjsonDemo {
    public static void main(String[] args) {
        // ---------- 1. 序列化:对象/Map/List 转 JSON 字符串 ----------
        User user = new User("张三", 25, new Date());
        String jsonString = JSON.toJSONString(user);
        System.out.println("对象转JSON: " + jsonString);
        // 输出: {"age":25,"createTime":"2026-08-20 15:30:00","user_name":"张三"}

        Map<String, Object> map = new HashMap<>();
        map.put("id", 1001);
        map.put("name", "李四");
        String mapJson = JSON.toJSONString(map);
        System.out.println("Map转JSON: " + mapJson);

        List<User> userList = Arrays.asList(user, new User("王五", 30, new Date()));
        String listJson = JSON.toJSONString(userList);
        System.out.println("List转JSON: " + listJson);

        // ---------- 2. 反序列化:JSON字符串 转 对象/List/Map ----------
        String json = "{\"user_name\":\"赵六\",\"age\":28,\"createTime\":\"2026-08-20 10:00:00\"}";
        User parsedUser = JSON.parseObject(json, User.class);
        System.out.println("JSON转对象: " + parsedUser.getName());

        // JSON字符串 转 List
        String jsonArray = "[{\"user_name\":\"A\",\"age\":1},{\"user_name\":\"B\",\"age\":2}]";
        List<User> parsedList = JSON.parseArray(jsonArray, User.class);
        System.out.println("JSON转List, 第一个用户名: " + parsedList.get(0).getName());

        // JSON字符串 转 Map
        Map<String, Object> parsedMap = JSON.parseObject(json);
        System.out.println("JSON转Map, 用户名: " + parsedMap.get("user_name"));

        // ---------- 3. 构造 JSON 请求体(常用) ----------
        JSONObject requestBody = new JSONObject();
        requestBody.put("username", "test_user");
        requestBody.put("password", "123456");
        requestBody.put("remember", true);
        
        String postJson = requestBody.toJSONString();
        System.out.println("构造的POST请求体: " + postJson);
        // 输出: {"remember":true,"password":"123456","username":"test_user"}

        // ---------- 4. 从 JSONObject 中提取数据 ----------
        JSONObject responseObj = JSON.parseObject("{\"code\":200,\"data\":{\"token\":\"abc123\"}}");
        int code = responseObj.getInteger("code");
        String token = responseObj.getJSONObject("data").getString("token");
        System.out.println("状态码: " + code + ", Token: " + token);
    }
}
posted @ 2026-08-07 10:24  FengweiTech  阅读(6)  评论(0)    收藏  举报