Java class library core framework application case sharing
Java class library core framework application case sharing
Java is a high -level programming language with cross -platform characteristics and extensive application areas.The Java class library is a commonly used tool set in Java development, which provides many common functions and data structures.This article will share some common application cases of the core framework of the Java library and provide the corresponding Java code example.
1. IO class library
Class Io library is the core library used to process the input and output in Java.A common application case is file operation.Here are a simple example to demonstrate how to read the content of the file and print it to the console.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Collections class library
The Collections class library provides a series of practical data structures and algorithms for managing and operating data sets.A common application case is to sort the list.The following is an example, showing how to sort a string list with the collections.sort method.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Tom");
names.add("Alice");
names.add("Bob");
Collections.sort(names);
for (String name : names) {
System.out.println(name);
}
}
}
3. JDBC class library
JDBC is a standard interface for the Java connection database, which provides a method of accessing relational databases.The following example shows how to use JDBC to connect to the MySQL database and perform simple query operations.
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, username, password)) {
String query = "SELECT * FROM users";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This article introduces three common application cases of the core framework of the Java library: the file operation of the IO class library, the list sorting of the Collections class library, and the database access of the JDBC class library.Through these cases, you can better understand and apply the core framework of the Java class library.Hope this article will be helpful to you.