欢迎访问宙启技术站
智能推送

Java内置函数库的常见用法

发布时间:2023-05-28 15:56:32

Java内置函数库是Java语言自带的函数库,包含众多常用的函数,方便开发人员快速开发和实现各种应用。下面是Java内置函数库的常见用法。

1.字符串处理

字符串是Java中常用的数据类型,Java内置函数库提供了很多函数来处理字符串,如字符串截取、比较、连接、替换等。

字符串截取:

String str = "hello world";

String substr = str.substring(0, 5); //截取字符串中的前5个字符

System.out.println(substr); //输出"hello"

字符串比较:

String str1 = "hello";

String str2 = "hello";

if (str1.equals(str2)) {

    System.out.println("两个字符串相同");

}

字符串连接:

String str1 = "hello";

String str2 = "world";

String result = str1 + " " + str2;

System.out.println(result); //输出"hello world"

字符串替换:

String str = "hello, world";

String result = str.replace("hello", "hi");

System.out.println(result); //输出"hi, world"

2.数学运算

Java内置函数库提供了大量的数学函数,包括常见的数学函数、随机数生成器和高精度计算相关函数。

取整函数:

double num = 3.14159;

int result = (int) num; //转化为整数

System.out.println(result); //输出"3"

随机数生成:

Random rand = new Random();

int num = rand.nextInt(100); //生成0-99之间的随机整数

System.out.println(num);

高精度计算:

BigDecimal num1 = new BigDecimal("3.14159");

BigDecimal num2 = new BigDecimal("2.71828");

BigDecimal result = num1.add(num2); //高精度计算,求和

System.out.println(result); //输出"5.85987"

3.日期处理

Java内置函数库提供了一系列处理日期和时间的函数,方便操作时间戳、时间格式化、时区转换等。

获取当前时间:

Date date = new Date();

System.out.println(date); //输出当前时间

时间格式化:

SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

String result = format.format(date); //格式化日期

System.out.println(result); //输出"2022年02月22日 12:34:56"

时区转换:

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8")); //设置时区为东八区

Calendar cal = Calendar.getInstance(TimeZone.getDefault());

System.out.println(cal.getTime()); //输出当前时间

4.文件操作

Java内置函数库提供了大量的文件操作函数,包括文件读写、文件夹创建、删除、重命名等。

文件读写:

File file = new File("test.txt"); //打开文件

FileWriter writer = new FileWriter(file);

writer.write("hello, world"); //写入字符串

writer.close();

文件夹创建:

File dir = new File("test");

if (!dir.exists()) {

    dir.mkdir(); //创建文件夹

}

5.网络操作

Java内置函数库提供了大量的网络通信相关函数,包括URL处理、HTTP协议发送、Socket通信等。

URL处理:

URL url = new URL("http://www.example.com"); //打开URL连接

URLConnection conn = url.openConnection();

HTTP协议发送:

URL url = new URL("http://www.example.com");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

Socket通信:

Socket socket = new Socket("localhost", 8080); //建立连接

OutputStream os = socket.getOutputStream();

os.write("hello, world".getBytes()); //发送数据

socket.close(); //关闭连接

总之,Java内置函数库是Java开发常用的函数库之一,配合良好的IDE和第三方库,能够为开发人员带来非常大的帮助。