欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > Java 常用类库详解

Java 常用类库详解

2024/10/24 16:31:44 来源:https://blog.csdn.net/fudaihb/article/details/139740397  浏览:    关键词: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 核心类库、集合框架、并发编程、网络编程、日期和时间处理以及常用的第三方库。通过这些类库,开发者可以高效地完成各种编程任务。希望本文能够帮助读者更好地理解和使用这些类库,从而提高开发效率和代码质量。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com