21xrx.com
2025-04-12 23:05:17 Saturday
文章检索 我的文章 写文章
Java如何存储数据 教你Java数据存储的代码实现
2023-06-16 10:14:32 深夜i     12     0
Java数据存储 文件存储 数据库存储 缓存

在Java编程中,数据存储是非常常见且重要的操作。Java提供了多种存储数据的方式,包括文件、数据库等。下面我们将介绍Java中存储数据的常用方式及相关代码实现。

1. 使用文件存储数据

Java中使用文件存储数据是最简单的方法之一。可以使用Java中的File、FileOutputStream和FileInputStream类实现。具体代码如下:

//写入数据
try {
  FileOutputStream fos=new FileOutputStream("data.txt",true);
  OutputStreamWriter osw=new OutputStreamWriter(fos);
  osw.write("你好Java!\n");
  osw.flush();
  fos.flush();
  osw.close();
  fos.close();      
} catch (IOException e) {
  e.printStackTrace();
}
//读取数据
try {
  FileInputStream fis=new FileInputStream("data.txt");
  InputStreamReader isr=new InputStreamReader(fis);
  BufferedReader br=new BufferedReader(isr);
  String str="";
  while((str=br.readLine())!=null){
    System.out.println(str);
  }
  br.close();
  isr.close();
  fis.close();      
} catch (IOException e) {
  e.printStackTrace();
}

2. 使用数据库存储数据

在Java中,使用数据库存储数据是非常常见的操作。Java中常用的数据库有MySQL、Oracle等。可以使用Java中的JDBC API操作数据库。具体代码如下:

//连接数据库
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
//插入数据
try {
  Statement st=conn.createStatement();
  String sql="insert into user(name,password) values('Tom','123456')";
  int i=st.executeUpdate(sql);
  System.out.println(i);
  st.close();
} catch (SQLException e) {
  e.printStackTrace();
}
//查询数据
try {
  Statement st=conn.createStatement();
  String sql="select * from user";
  ResultSet rs=st.executeQuery(sql);
  while(rs.next()){
    System.out.println(rs.getString("name")+","+rs.getString("password"));
  }
  rs.close();
  st.close();     
} catch (SQLException e) {
  e.printStackTrace();
}
//关闭连接
conn.close();

3. 使用缓存存储数据

在Java中,使用缓存存储数据可以提高数据读取的效率。Java提供了Ehcache和Redis等缓存框架。具体代码如下:

//使用Ehcache缓存数据
Cache cache = manager.getCache("myCache");
Element element = new Element("key1", "value1");
cache.put(element);
System.out.println(cache.get("key1").getObjectValue());
//使用Redis缓存数据
Jedis jedis = new Jedis("localhost");
jedis.set("key1", "value1");
System.out.println(jedis.get("key1"));
jedis.close();

  
  

评论区