【Java编程动手学】Java常用工具类
文章目录
- Java常用工具类
- 一、字符串类(String)
- 1、常用方法
- 示例代码
- 二、运行环境类(Runtime)
- 常用方法
- 示例代码
- 三、系统类(System)
- 常用方法
- 示例代码
- 四、数学类(Math)
- 常用方法
- 示例代码
- 五、随机数类(Random)
- 常用方法
- 示例代码
- 六、扫描类(Scanner)
- 常用方法
- 示例代码
- 七、日期类(Date)
- 常用方法
- 示例代码
- 八、正则表达式
- 常用类和方法
- 示例代码
- 九、其他工具类
- 示例代码(Arrays和Collections)
- 总结
Java常用工具类
引言
在Java编程中,工具类是提高开发效率、简化代码的重要手段。Java标准库中提供了大量的工具类,涵盖了字符串处理、系统操作、数学计算、随机数生成、日期时间处理、正则表达式等多个方面。本文将详细介绍Java常用工具类的使用方法和示例代码,帮助读者更好地掌握这些工具类,提升编程技能。
一、字符串类(String)
字符串是编程中最基本的数据类型之一,Java中的String类提供了大量的方法来处理字符串。
1、常用方法
方法名 | 描述 |
---|---|
charAt() | 返回指定索引处的字符 |
length() | 返回字符串的长度 |
equals() | 比较两个字符串是否相等 |
startsWith() | 检查字符串是否以指定的前缀开始 |
endsWith() | 检查字符串是否以指定的后缀结束 |
indexOf() | 返回指定字符或子字符串的索引 |
substring() | 截取字符串的一部分 |
replace() | 替换字符串中的字符或子字符串 |
split() | 根据指定的分隔符分割字符串 |
toLowerCase() | 将字符串转换为小写 |
toUpperCase() | 将字符串转换为大写 |
concat() | 连接两个字符串 |
trim() | 去除字符串两端的空白字符 |
示例代码
public class StringExample {public static void main(String[] args) {String str = "Hello, World!";System.out.println("charAt(7): " + str.charAt(7)); // 输出 'W'System.out.println("length: " + str.length()); // 输出 13System.out.println("equals: " + str.equals("hello, world!")); // 输出 falseSystem.out.println("startsWith Hello: " + str.startsWith("Hello")); // 输出 trueSystem.out.println("endsWith World!: " + str.endsWith("World!")); // 输出 trueSystem.out.println("indexOf 'o': " + str.indexOf('o')); // 输出 4System.out.println("substring(7,12): " + str.substring(7,12)); // 输出 "World"System.out.println("replace 'l' with 'L': " + str.replace('l', 'L')); // 输出 "HeLLo, WorLd!"System.out.println("split ', ': " + java.util.Arrays.toString(str.split(", "))); // 输出 ["Hello", "World!"]System.out.println("toLowerCase: " + str.toLowerCase()); // 输出 "hello, world!"System.out.println("toUpperCase: " + str.toUpperCase()); // 输出 "HELLO, WORLD!"System.out.println("concat '!!!': " + str.concat("!!!")); // 输出 "Hello, World!!!!"System.out.println("trim: " + " Hello, World! ".trim()); // 输出 "Hello, World!"}
}
二、运行环境类(Runtime)
Runtime类提供了与Java运行时环境交互的方法,允许程序获取系统信息、执行外部命令等。
常用方法
方法名 | 描述 |
---|---|
getRuntime() | 返回当前运行时环境 |
availableProcessors() | 返回可用处理器的数量 |
freeMemory() | 返回JVM可用的内存量 |
totalMemory() | 返回JVM占用的内存总量 |
maxMemory() | 返回JVM可以使用的最大内存量 |
gc() | 运行垃圾回收器 |
exec(String command) | 执行指定的外部命令 |
示例代码
public class RuntimeExample {public static void main(String[] args) {Runtime runtime = Runtime.getRuntime();System.out.println("Available processors: " + runtime.availableProcessors());System.out.println("Free memory: " + runtime.freeMemory() + " bytes");System.out.println("Total memory: " + runtime.totalMemory() + " bytes");System.out.println("Max memory: " + runtime.maxMemory() + " bytes");// 执行外部命令(例如,在Windows上执行“dir”命令,在Linux或Mac上执行“ls”命令)try {Process process = runtime.exec("dir"); // Windows// Process process = runtime.exec("ls"); // Linux/Macjava.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(process.getInputStream()));String line;while ((line = reader.readLine()) != null) {System.out.println(line);}} catch (Exception e) {e.printStackTrace();}}
}
三、系统类(System)
System类提供了与系统相关的功能,如获取系统属性、环境变量、标准输入输出等。
常用方法
方法名 | 描述 |
---|---|
currentTimeMillis() | 返回当前时间(毫秒) |
getProperty(String key) | 获取系统属性 |
getenv(String name) | 获取环境变量 |
exit(int status) | 退出Java虚拟机 |
arraycopy(Object src, int srcPos, Object dest, int destPos, int length) | 复制数组 |
gc() | 运行垃圾回收器(与Runtime的gc()方法类似) |
示例代码
public class SystemExample {public static void main(String[] args) {System.out.println("Current time in milliseconds: " + System.currentTimeMillis());System.out.println("Java version: " + System.getProperty("java.version"));System.out.println("OS name: " + System.getProperty("os.name"));System.out.println("PATH environment variable: " + System.getenv("PATH"));// 数组复制示例int[] srcArray = {1, 2, 3, 4, 5};int[] destArray = new int[5];System.arraycopy(srcArray, 0, destArray, 0, 5);System.out.print("Copied array: ");for (int i : destArray) {System.out.print(i + " ");}System.out.println();// 退出程序(状态码为0表示正常退出)// System.exit(0);}
}
四、数学类(Math)
Math类提供了基本的数学运算和常数,如三角函数、对数、指数、平方根等。
常用方法
方法名 | 描述 |
---|---|
abs() | 返回绝对值 |
sqrt() | 返回平方根 |
pow() | 返回幂值 |
sin()、cos()、tan() | 三角函数 |
log() | 自然对数 |
log10() | 底数为10的对数 |
exp() | 自然指数 |
PI | 圆周率常数 |
E | 自然常数 |
示例代码
public class MathExample {public static void main(String[] args) {System.out.println("Absolute value of -10: " + Math.abs(-10));System.out.println("Square root of 16: " + Math.sqrt(16));System.out.println("2 raised to the power of 3: " + Math.pow(2, 3));System.out.println("Sine of 0: " + Math.sin(0));System.out.println("Cosine of 0: " + Math.cos(0));System.out.println("Tangent of 0: " + Math.tan(0));System.out.println("Natural logarithm of E: " + Math.log(Math.E));System.out.println("Logarithm base 10 of 100: " + Math.log10(100));System.out.println("Exponential of 1: " + Math.exp(1));System.out.println("PI: " + Math.PI);System.out.println("E: " + Math.E);}
}
五、随机数类(Random)
Random类用于生成伪随机数,可以生成整数、浮点数、布尔值等类型的随机数。
常用方法
方法名 | 描述 |
---|---|
nextInt() | 返回随机整数 |
nextDouble() | 返回随机双精度浮点数 |
nextBoolean() | 返回随机布尔值 |
nextFloat() | 返回随机单精度浮点数 |
nextLong() | 返回随机长整数 |
nextBytes(byte[] bytes) | 生成随机字节并存储到指定的数组中 |
示例代码
import java.util.Random;public class RandomExample {public static void main(String[] args) {Random random = new Random();System.out.println("Random integer: " + random.nextInt());System.out.println("Random double: " + random.nextDouble());System.out.println("Random boolean: " + random.nextBoolean());System.out.println("Random float: " + random.nextFloat());System.out.println("Random long: " + random.nextLong());// 生成随机字节数组byte[] bytes = new byte[5];random.nextBytes(bytes);System.out.print("Random bytes: ");for (byte b : bytes) {System.out.print(b + " ");}System.out.println();}
}
六、扫描类(Scanner)
Scanner类用于解析基本类型和字符串的简单文本扫描器,可以从输入流(如System.in)中读取数据。
常用方法
方法名 | 描述 |
---|---|
nextInt() | 扫描下一个整数标记 |
nextDouble() | 扫描下一个双精度浮点数标记 |
nextLine() | 扫描下一行文本 |
next() | 扫描下一个标记(默认以空白字符为分隔符) |
hasNext() | 检查输入中是否还有其他标记 |
close() | 关闭扫描器 |
示例代码
import java.util.Scanner;public class ScannerExample {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("Enter an integer: ");int num = scanner.nextInt();System.out.println("You entered: " + num);System.out.println("Enter a double: ");double d = scanner.nextDouble();System.out.println("You entered: " + d);System.out.println("Enter a line of text: ");String line = scanner.nextLine(); // 注意,这里可能需要处理换行符的问题// 更安全的做法是,在读取完数字后,先调用一次nextLine()来消耗掉换行符// 但为了示例简单,这里直接再次调用nextLine(),可能需要用户输入两次// 更好的方式是在读取数字后,立即调用一个额外的nextLine()来消耗换行符// 下面是一种修正方式:// ...// 修正后的代码示例(放在上面代码之前读取line的情况,这里仅作说明,实际应调整顺序)// 由于已经读取了数字,换行符还在输入流中,所以直接读取line会得到空字符串// 因此,我们需要先消耗掉换行符scanner.nextLine(); // 消耗掉换行符System.out.println("Enter a line of text (corrected): ");line = scanner.nextLine();System.out.println("You entered: " + line);scanner.close();}
}
// 更合理的代码结构示例(避免换行符问题):
/*
import java.util.Scanner;public class ScannerExample {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("Enter an integer: ");int num = scanner.nextInt();scanner.nextLine(); // 消耗掉换行符System.out.println("You entered: " + num);System.out.println("Enter a line of text: ");String line = scanner.nextLine();System.out.println("You entered: " + line);scanner.close();}
}
*/
七、日期类(Date)
Date类用于表示特定的瞬间,精确到毫秒。虽然Date类现在被推荐使用更现代的日期时间API(如java.time包中的类)替代,但在一些旧代码中仍然可以看到它的使用。
常用方法
方法名 | 描述 |
---|---|
getTime() | 返回自1970年1月1日 00:00:00 GMT以来的毫秒数 |
toString() | 将日期转换为字符串 |
after(Date when) | 判断当前日期是否在指定日期之后 |
before(Date when) | 判断当前日期是否在指定日期之前 |
示例代码
import java.util.Date;public class DateExample {public static void main(String[] args) {Date date = new Date();System.out.println("Current date and time: " + date.toString());System.out.println("Time in milliseconds: " + date.getTime());Date pastDate = new Date(0); // 1970年1月1日 00:00:00 GMTSystem.out.println("Past date: " + pastDate.toString());System.out.println("Current date is after past date: " + date.after(pastDate));System.out.println("Current date is before past date: " + date.before(pastDate)); // 输出 false}
}
八、正则表达式
Java中的正则表达式主要通过Pattern
和Matcher
类来实现,用于字符串的匹配、查找、替换等操作。
常用类和方法
类名/方法名 | 描述 |
---|---|
Pattern.compile(String regex) | 编译正则表达式 |
Matcher.matches() | 尝试将整个区域与模式匹配 |
Matcher.find() | 扫描输入序列以查找与该模式匹配的下一个子序列 |
Matcher.group() | 返回由以前匹配操作所匹配的输入子序列 |
Matcher.start() | 返回以前匹配的初始索引 |
Matcher.end() | 返回最后匹配字符之后的偏移量 |
示例代码
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class RegexExample {public static void main(String[] args) {String text = "This is a sample text with 12345 and 67890";String regex = "\\d+"; // 匹配一个或多个数字Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(text);while (matcher.find()) {System.out.println("Found: " + matcher.group() + " at index " + matcher.start() + " to " + matcher.end());}// 替换示例String replacedText = text.replaceAll("\\d+", "NUMBER");System.out.println("Replaced text: " + replacedText);}
}
九、其他工具类
除了上述工具类外,Java标准库中还有许多其他有用的工具类,如:
- Arrays:用于操作数组的工具类,提供排序、查找、填充等功能。
- Collections:用于操作集合的工具类,提供排序、查找、同步包装等功能。
- Objects:提供用于操作对象的实用方法,如比较、哈希码生成等。
示例代码(Arrays和Collections)
import java.util.Arrays;
import java.util.Collections;
import java.util.List;public class OtherToolsExample {public static void main(String[] args) {// Arrays示例int[] intArray = {3, 1, 4, 1, 5, 9, 2, 6};Arrays.sort(intArray);System.out.println("Sorted int array: " + Arrays.toString(intArray));// Collections示例List<String> list = Arrays.asList("apple", "banana", "cherry", "date");Collections.sort(list);System.out.println("Sorted list: " + list);Collections.reverse(list);System.out.println("Reversed list: " + list);}
}
总结
Java常用工具类为开发者提供了强大的功能,使得处理字符串、数学运算、随机数生成、日期处理、正则表达式等任务变得更加简单和高效。通过掌握这些工具类,开发者可以更加专注于业务逻辑的实现,提高开发效率。本文详细介绍了Java中的一些常用工具类,并提供了相应的代码示例,希望对读者有所帮助。在实际开发中,建议根据具体需求选择合适的工具类,并参考Java官方文档以获取更详细的信息。