Java 常用类库详解

2024-06-18 19:52
文章标签 java 详解 常用 类库

本文主要是介绍Java 常用类库详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  1. Java 核心类库
    1. java.lang
    2. java.util
    3. java.io
    4. java.nio
  2. 集合框架
    1. List 接口及其实现类
    2. Set 接口及其实现类
    3. Map 接口及其实现类
  3. 并发编程
    1. java.util.concurrent
    2. Atomic 类
    3. Lock 类
  4. 网络编程
    1. java.net
    2. HttpClient
  5. 日期和时间处理
    1. java.util.Date 和 java.util.Calendar
    2. java.time
  6. 常用第三方库
    1. Apache Commons
    2. Google Guava
    3. Jackson
  7. 总结

Java 核心类库

java.lang

java.lang 是 Java 核心类库中最基础的部分,包含了 Java 编程的核心类。常用的类有:

  • String:表示字符串的类。
  • Math:包含基本数学运算方法的类。
  • System:包含标准输入、输出、错误输出流,访问外部属性和环境的方法。
  • Thread:实现多线程的类。
  • Object:所有类的父类,包含对象的基本方法。
示例代码
public class LangExample {public static void main(String[] args) {// String 操作String greeting = "Hello, World!";System.out.println(greeting.toUpperCase());// Math 操作double randomValue = Math.random();System.out.println("Random Value: " + randomValue);// System 操作System.out.println("Current Time: " + System.currentTimeMillis());// Thread 操作Thread thread = new Thread(() -> System.out.println("Thread Running"));thread.start();// Object 操作Object obj = new Object();System.out.println(obj.toString());}
}

java.util

java.util 包含了集合框架、日期和时间、随机数生成等常用工具类。

  • ArrayList:动态数组实现类。
  • HashMap:基于哈希表的 Map 接口实现。
  • Calendar:日期和时间的抽象类。
  • Random:用于生成伪随机数。
示例代码
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Calendar;
import java.util.Random;public class UtilExample {public static void main(String[] args) {// ArrayList 操作ArrayList<String> list = new ArrayList<>();list.add("Apple");list.add("Banana");System.out.println(list);// HashMap 操作HashMap<String, Integer> map = new HashMap<>();map.put("Apple", 1);map.put("Banana", 2);System.out.println(map);// Calendar 操作Calendar calendar = Calendar.getInstance();System.out.println("Current Time: " + calendar.getTime());// Random 操作Random random = new Random();System.out.println("Random Number: " + random.nextInt(100));}
}

java.io

java.io 提供了系统输入、输出、文件操作等 I/O 功能。

  • File:表示文件和目录路径名的抽象表示。
  • FileInputStream:用于读取文件的输入流。
  • FileOutputStream:用于写入文件的输出流。
  • BufferedReader:缓冲读取字符的输入流。
示例代码
import java.io.*;public class IOExample {public static void main(String[] args) {// File 操作File file = new File("example.txt");try {if (file.createNewFile()) {System.out.println("File created: " + file.getName());} else {System.out.println("File already exists.");}// FileOutputStream 操作FileOutputStream fos = new FileOutputStream(file);fos.write("Hello, World!".getBytes());fos.close();// FileInputStream 操作FileInputStream fis = new FileInputStream(file);int i;while ((i = fis.read()) != -1) {System.out.print((char) i);}fis.close();// BufferedReader 操作BufferedReader br = new BufferedReader(new FileReader(file));String line;while ((line = br.readLine()) != null) {System.out.println(line);}br.close();} catch (IOException e) {e.printStackTrace();}}
}

java.nio

java.nio (New I/O) 是 Java 1.4 引入的新的 I/O API,提供了更高效的 I/O 操作。

  • ByteBuffer:字节缓冲区,读写缓冲区中的字节。
  • FileChannel:与文件、内存映射文件、文件锁定有关的通道。
  • Selector:用于多路复用选择的选择器。
示例代码
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class NIOExample {public static void main(String[] args) {try {// 创建 ByteBufferByteBuffer buffer = ByteBuffer.allocate(48);buffer.put("Hello, NIO!".getBytes());buffer.flip();// 写入文件FileOutputStream fos = new FileOutputStream("nio-example.txt");FileChannel channel = fos.getChannel();channel.write(buffer);channel.close();fos.close();// 读取文件FileInputStream fis = new FileInputStream("nio-example.txt");FileChannel readChannel = fis.getChannel();ByteBuffer readBuffer = ByteBuffer.allocate(48);readChannel.read(readBuffer);readBuffer.flip();while (readBuffer.hasRemaining()) {System.out.print((char) readBuffer.get());}readChannel.close();fis.close();} catch (IOException e) {e.printStackTrace();}}
}

集合框架

Java 集合框架提供了一组用于存储和操作数据的类和接口,包括 ListSetMap 等。以下是一些常用集合类的详细介绍。

List 接口及其实现类

List 接口表示一个有序的集合,允许重复的元素。常见的实现类有:

  • ArrayList:基于数组实现的列表,支持快速随机访问。
  • LinkedList:基于链表实现的列表,适合频繁插入和删除操作。
示例代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;public class ListExample {public static void main(String[] args) {// ArrayList 操作List<String> arrayList = new ArrayList<>();arrayList.add("Apple");arrayList.add("Banana");System.out.println("ArrayList: " + arrayList);// LinkedList 操作List<String> linkedList = new LinkedList<>();linkedList.add("Cherry");linkedList.add("Date");System.out.println("LinkedList: " + linkedList);}
}

Set 接口及其实现类

Set 接口表示一个不允许重复元素的集合。常见的实现类有:

  • HashSet:基于哈希表实现的集合,允许快速查找。
  • TreeSet:基于红黑树实现的集合,保证元素的有序性。
示例代码
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;public class SetExample {public static void main(String[] args) {// HashSet 操作Set<String> hashSet = new HashSet<>();hashSet.add("Apple");hashSet.add("Banana");hashSet.add("Apple"); // 重复元素不会被添加System.out.println("HashSet: " + hashSet);// TreeSet 操作Set<String> treeSet = new TreeSet<>();treeSet.add("Cherry");treeSet.add("Date");treeSet.add("Banana");System.out.println("TreeSet: " + treeSet);}
}

Map 接口及其实现类

Map 接口表示一个键值对映射的集合。常见的实现类有:

  • HashMap:基于哈希表实现的映射,允许快速查找。
  • TreeMap:基于红黑树实现的映射,保证键的有序性。
示例代码
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;public class MapExample {public static void main(String[] args) {// HashMap 操作Map<String, Integer> hashMap = new HashMap<>();hashMap.put("Apple", 1);hashMap.put("Banana", 2);System.out.println("HashMap: " + hashMap);// TreeMap 操作Map<String, Integer> treeMap = new TreeMap<>();treeMap.put("Cherry", 3);treeMap.put("Date", 4);System.out.println("TreeMap: " + treeMap);}
}

并发编程

并发编程是 Java 的一大特点,Java 提供了一整套并发编程的工具和类。

java.util.concurrent

java.util.concurrent 包含了并发编程所需的类和接口,例如线程池、同步工具等。

  • ExecutorService:框架中用于执行异步任务的接口。
  • CountDownLatch:允许一个或多个线程等待其他线程完成操作的同步辅助工具。
  • ConcurrentHashMap:线程安全的哈希表。
示例代码
import java.util.concurrent.*;public class ConcurrentExample {public static void main(String[] args) {// ExecutorService 操作ExecutorService executor = Executors.newFixedThreadPool(2);executor.submit(() -> System.out.println("Task 1"));executor.submit(() -> System.out.println("Task 2"));executor.shutdown();// CountDownLatch 操作CountDownLatch latch = new CountDownLatch(2);new Thread(() -> {System.out.println("Thread 1");latch.countDown();}).start();new Thread(() -> {System.out.println("Thread 2");latch.countDown();}).start();try {latch.await();System.out.println("All threads finished");} catch (InterruptedException e) {e.printStackTrace();}// ConcurrentHashMap 操作ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();map.put("Apple", 1);map.put("Banana", 2);System.out.println("ConcurrentHashMap: " + map);}
}

Atomic 类

java.util.concurrent.atomic 提供了一些用于并发编程的原子类,确保在多线程环境下对变量的操作是原子性的。

  • AtomicInteger:提供对 int 类型的原子操作。
  • AtomicBoolean:提供对 boolean 类型的原子操作。
示例代码
import java.util.concurrent.atomic.AtomicInteger;public class AtomicExample {public static void main(String[] args) {// AtomicInteger 操作AtomicInteger atomicInt = new AtomicInteger(0);System.out.println("Initial Value: " + atomicInt.get());atomicInt.incrementAndGet();System.out.println("After Increment: " + atomicInt.get());}
}

Lock 类

java.util.concurrent.locks 包含了一些用于控制多线程访问共享资源的锁类。

  • ReentrantLock:一个可重入的互斥锁。
  • ReadWriteLock:读写锁,允许多个读线程同时访问,但写线程独占访问。
示例代码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class LockExample {private static int counter = 0;private static final Lock lock = new ReentrantLock();public static void main(String[] args) {Runnable task = () -> {lock.lock();try {counter++;System.out.println("Counter: " + counter);} finally {lock.unlock();}};Thread thread1 = new Thread(task);Thread thread2 = new Thread(task);thread1.start();thread2.start();}
}

网络编程

Java 提供了丰富的类库来支持网络编程,包括传统的 java.net 和更现代的 HttpClient

java.net

java.net 包含了进行网络操作的类,如 SocketServerSocketURL 等。

  • Socket:实现客户端和服务器之间的通信。
  • ServerSocket:实现服务器端的监听。
示例代码
import java.net.*;
import java.io.*;public class NetworkExample {public static void main(String[] args) {try {// 启动服务器new Thread(() -> {try (ServerSocket serverSocket = new ServerSocket(8080)) {Socket socket = serverSocket.accept();BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));System.out.println("Server received: " + in.readLine());} catch (IOException e) {e.printStackTrace();}}).start();// 启动客户端Thread.sleep(1000); // 等待服务器启动try (Socket socket = new Socket("localhost", 8080)) {PrintWriter out = new PrintWriter(socket.getOutputStream(), true);out.println("Hello, Server!");}} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

HttpClient

java.net.http.HttpClient 是 Java 11 引入的新特性,用于发送 HTTP 请求和接收响应。

示例代码
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;public class HttpClientExample {public static void main(String[] args) {HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://jsonplaceholder.typicode.com/posts/1")).build();try {HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());System.out.println("Response: " + response.body());} catch (IOException | InterruptedException e) {e.printStackTrace();}}
}

日期和时间处理

Java 提供了多种类来处理日期和时间,从早期的 java.util.Datejava.util.Calendar 到现代的 java.time

java.util.Date 和 java.util.Calendar

这些类是早期 Java 中处理日期和时间的主要工具。

示例代码
import java.util.Date;
import java.util.Calendar;public class DateExample {public static void main(String[] args) {// Date 操作Date date = new Date();System.out.println("Current Date: " + date);// Calendar 操作Calendar calendar = Calendar.getInstance();System.out.println("Current Time: " + calendar.getTime());}
}

java.time

java.time 包含了一套新的日期和时间 API,是 Java 8 引入的,提供了更好的日期和时间处理能力。

  • LocalDate:表示日期,无时间部分。
  • LocalTime:表示时间,无日期部分。
  • LocalDateTime:表示日期和时间。
  • ZonedDateTime:表示带时区的日期和时间。
示例代码
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;public class TimeExample {public static void main(String[] args) {// LocalDate 操作LocalDate date = LocalDate.now();System.out.println("Current Date: " + date);// LocalTime 操作LocalTime time = LocalTime.now();System.out.println("Current Time: " + time);// LocalDateTime 操作LocalDateTime dateTime = LocalDateTime.now();System.out.println("Current DateTime: " + dateTime);// ZonedDateTime 操作ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("America/New_York"));System.out.println("Current ZonedDateTime: " + zonedDateTime);}
}

常用第三方库

除了 Java 标准库外,许多第三方库也在 Java 开发中被广泛使用,如 Apache Commons、Google Guava 和 Jackson 等。

Apache Commons

Apache Commons 提供了许多实用的类库,涵盖了各种常见的开发需求。

  • Commons Lang:扩展了 java.lang 包的功能。
  • Commons IO:提供了对 I/O 操作的支持。
  • Commons Collections

:扩展了 Java 的集合框架。

示例代码
import org.apache.commons.lang3.StringUtils;public class CommonsExample {public static void main(String[] args) {// StringUtils 操作String str = "  Hello, Commons!  ";System.out.println("Trimmed String: '" + StringUtils.trim(str) + "'");}
}

Google Guava

Google Guava 提供了许多有用的工具类和方法。

  • Lists:处理列表的工具类。
  • Maps:处理映射的工具类。
  • Preconditions:用于参数验证。
示例代码
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.base.Preconditions;import java.util.List;
import java.util.Map;public class GuavaExample {public static void main(String[] args) {// Lists 操作List<String> list = Lists.newArrayList("Apple", "Banana", "Cherry");System.out.println("List: " + list);// Maps 操作Map<String, Integer> map = Maps.newHashMap();map.put("Apple", 1);map.put("Banana", 2);System.out.println("Map: " + map);// Preconditions 操作String str = "Hello, Guava!";Preconditions.checkNotNull(str, "String should not be null");System.out.println(str);}
}

Jackson

Jackson 是一个处理 JSON 数据的强大工具。

  • ObjectMapper:用于读写 JSON 数据。
示例代码
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;public class JacksonExample {public static void main(String[] args) {ObjectMapper mapper = new ObjectMapper();// 对象转 JSONMap<String, String> map = new HashMap<>();map.put("name", "John");map.put("age", "30");try {String json = mapper.writeValueAsString(map);System.out.println("JSON: " + json);// JSON 转对象Map<String, String> resultMap = mapper.readValue(json, HashMap.class);System.out.println("Map: " + resultMap);} catch (IOException e) {e.printStackTrace();}}
}

总结

本文详细介绍了 Java 开发中常用的类库,包括 Java 核心类库、集合框架、并发编程、网络编程、日期和时间处理以及常用的第三方库。通过这些类库,开发者可以高效地完成各种编程任务。希望本文能够帮助读者更好地理解和使用这些类库,从而提高开发效率和代码质量。

这篇关于Java 常用类库详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1072952

相关文章

Java中StopWatch的使用示例详解

《Java中StopWatch的使用示例详解》stopWatch是org.springframework.util包下的一个工具类,使用它可直观的输出代码执行耗时,以及执行时间百分比,这篇文章主要介绍... 目录stopWatch 是org.springframework.util 包下的一个工具类,使用它

Java进行文件格式校验的方案详解

《Java进行文件格式校验的方案详解》这篇文章主要为大家详细介绍了Java中进行文件格式校验的相关方案,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、背景异常现象原因排查用户的无心之过二、解决方案Magandroidic Number判断主流检测库对比Tika的使用区分zip

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

Tomcat版本与Java版本的关系及说明

《Tomcat版本与Java版本的关系及说明》:本文主要介绍Tomcat版本与Java版本的关系及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Tomcat版本与Java版本的关系Tomcat历史版本对应的Java版本Tomcat支持哪些版本的pythonJ