Bagaimana untuk melakukan ketekunan dan penyimpanan data dalam pembangunan Java, anda memerlukan contoh kod khusus
Dalam pembangunan Java, ketekunan dan penyimpanan data adalah bahagian yang sangat penting. Ia melibatkan menyimpan data ke cakera atau media berterusan lain supaya ia boleh terus digunakan apabila program dijalankan semula. Artikel ini akan memperkenalkan ketekunan biasa dan teknologi penyimpanan data dalam Java dan memberikan contoh kod.
1. Fail IO
Fail IO ialah salah satu kaedah penyimpanan data yang paling asas dan biasa digunakan. Dengan menggunakan aliran input dan output Java serta kelas pemprosesan fail, anda boleh menulis data ke fail dan membaca data daripada fail apabila diperlukan.
Contoh 1: Menggunakan fail IO untuk penyimpanan data
import java.io.File; import java.io.FileWriter; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class FileIODemo { public static void main(String[] args) { String data = "Hello, World!"; String fileName = "data.txt"; // 写入数据到文件 try { FileWriter writer = new FileWriter(fileName); writer.write(data); writer.close(); System.out.println("数据写入成功!"); } catch (IOException e) { e.printStackTrace(); } // 从文件中读取数据 try { FileReader reader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println("读取到数据:" + line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
Contoh 2: Menggunakan fail IO untuk menyimpan dan membaca objek
import java.io.Serializable; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.IOException; public class ObjectIODemo { public static void main(String[] args) { // 定义需要保存的对象 Person person = new Person("Alice", 20); // 将对象保存到文件 try { FileOutputStream fileOutputStream = new FileOutputStream("person.ser"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); objectOutputStream.writeObject(person); objectOutputStream.close(); System.out.println("对象保存成功!"); } catch (IOException e) { e.printStackTrace(); } // 从文件中读取对象 try { FileInputStream fileInputStream = new FileInputStream("person.ser"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Person restoredPerson = (Person) objectInputStream.readObject(); objectInputStream.close(); System.out.println("读取到对象:" + restoredPerson); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
2 Pangkalan data perhubungan ialah kaedah penyimpanan data yang cekap, berskala dan tahan lama. Java menyediakan pelbagai API untuk pangkalan data pengendalian, seperti JDBC (Java Database Connectivity) dan JPA (Java Persistence API).
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBCDemo { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydb"; String username = "root"; String password = "123456"; try { Connection connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); // 创建表 String createTableSQL = "CREATE TABLE IF NOT EXISTS employees (id INT PRIMARY KEY, name VARCHAR(50))"; statement.executeUpdate(createTableSQL); // 插入数据 String insertDataSQL = "INSERT INTO employees VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie')"; statement.executeUpdate(insertDataSQL); // 查询数据 String selectDataSQL = "SELECT * FROM employees"; ResultSet resultSet = statement.executeQuery(selectDataSQL); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); System.out.println("id: " + id + ", name: " + name); } statement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class JPADemo { public static void main(String[] args) { // 创建实体管理工厂 EntityManagerFactory factory = Persistence.createEntityManagerFactory("my-persistence-unit"); EntityManager entityManager = factory.createEntityManager(); // 创建事务 EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { // 创建实体对象 Person person1 = new Person("Alice", 20); Person person2 = new Person("Bob", 25); // 保存实体对象 entityManager.persist(person1); entityManager.persist(person2); // 提交事务 transaction.commit(); System.out.println("对象保存成功!"); } catch (Exception e) { e.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); factory.close(); } } } @Entity class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private int age; // 省略构造函数、getter和setter等 }
Atas ialah kandungan terperinci Bagaimana untuk melaksanakan ketekunan dan penyimpanan data dalam pembangunan Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!