Java内置函数的使用和示例代码
Java是一种面向对象编程语言,它提供了大量的内置函数和类库来方便程序员进行开发。这些内置函数和类库能够帮助我们处理字符串、日期、文件、网络等常用操作。在本文中,将介绍Java中几个常用的内置函数及其示例代码。
1. 字符串处理函数
Java中最常用的字符串处理函数包括substring、charAt、length和indexOf等函数。
substring函数能够截取字符串的一部分,示例代码如下:
String str = "Hello World"; String substr = str.substring(0, 5); System.out.println(substr); // 输出结果为Hello
charAt函数能够获取字符串中指定位置的字符,示例代码如下:
String str = "Hello World"; char ch = str.charAt(0); System.out.println(ch); // 输出结果为H
length函数能够获取字符串的长度,示例代码如下:
String str = "Hello World"; int len = str.length(); System.out.println(len); // 输出结果为11
indexOf函数能够查找指定字符串在源字符串中的位置,示例代码如下:
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index);
// 输出结果为6
2. 日期处理函数
Java中常用的日期处理函数包括SimpleDateFormat、Calendar和Date等函数。
SimpleDateFormat函数能够将字符串转换成日期类型,示例代码如下:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("2021-12-01");
System.out.println(date);
// 输出结果为Wed Dec 01 00:00:00 CST 2021
Calendar函数能够进行日期的加减运算,示例代码如下:
Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.DAY_OF_MONTH, 1); System.out.println(cal.getTime()); // 输出结果为明天的日期
Date函数能够获取系统当前时间,示例代码如下:
Date date = new Date(); System.out.println(date); // 输出结果为当前系统时间
3. 文件处理函数
Java中常用的文件处理函数包括File、BufferedReader和PrintWriter等函数。
File函数能够创建或者删除文件夹和文件,示例代码如下:
File file = new File("D:\\test.txt");
if(file.exists()) {
file.delete();
} else {
file.createNewFile();
}
BufferedReader函数能够读取文件内容,示例代码如下:
File file = new File("D:\\test.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
PrintWriter函数能够向文件中写入内容,示例代码如下:
File file = new File("D:\\test.txt");
PrintWriter writer = new PrintWriter(file);
writer.println("Hello World");
writer.close();
4. 网络处理函数
Java中常用的网络处理函数包括Socket和ServerSocket等函数。
Socket函数能够建立客户端与服务端之间的通信,示例代码如下:
Socket client = new Socket("localhost", 9999);
OutputStream out = client.getOutputStream();
out.write("Hello World".getBytes());
client.close();
ServerSocket函数能够建立服务端,监听客户端的请求,示例代码如下:
ServerSocket server = new ServerSocket(9999); Socket client = server.accept(); InputStream in = client.getInputStream(); byte[] data = new byte[1024]; int len = in.read(data); String str = new String(data, 0, len); System.out.println(str); client.close(); server.close();
总结
本文介绍了Java中常用的内置函数,包括字符串处理函数、日期处理函数、文件处理函数和网络处理函数等。这些内置函数能够大大简化Java程序的编写,提高开发效率,同时也让代码更加易读易懂。读者可以根据自己的需要,选择使用这些内置函数并加以灵活运用。
