java学习笔记-第四课

1. 输入输出操作
1.1 输入输出流的概念
  • 输入流(Input Stream):从数据源读取数据的流,如文件、键盘等。
  • 输出流(Output Stream):向数据目的地写入数据的流,如文件、显示器等。
  • 字节流和字符流
    • 字节流(InputStreamOutputStream)用于处理字节数据。
    • 字符流(ReaderWriter)用于处理字符数据。
1.2 文件操作
  • 读取文件

    import java.io.FileReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  • 写入文件

    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
                bw.write("Hello, World!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

1.3 序列化
  • 概念:将对象转换为字节流,以便存储或传输。

  • 实现

    import java.io.Serializable;
    
    public class Person implements Serializable {
        private static final long serialVersionUID = 1L;
        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 + '}';
        }
    }
    

  • 序列化和反序列化

    import java.io.FileOutputStream;
    import java.io.FileInputStream;
    import java.io.ObjectOutputStream;
    import java.io.ObjectInputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            Person person = new Person("John", 30);
    
            // 序列化
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
                oos.writeObject(person);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            // 反序列化
            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
                Person deserializedPerson = (Person) ois.readObject();
                System.out.println(deserializedPerson);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    

2. 文件和目录操作
  • 创建文件

    import java.io.File;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) {
            File file = new File("example.txt");
            try {
                if (file.createNewFile()) {
                    System.out.println("File created: " + file.getName());
                } else {
                    System.out.println("File already exists.");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

  • 创建目录

    import java.io.File;
    
    public class Main {
        public static void main(String[] args) {
            File dir = new File("exampleDir");
            if (dir.mkdir()) {
                System.out.println("Directory created: " + dir.getName());
            } else {
                System.out.println("Directory already exists.");
            }
        }
    }
    

  • 列出目录内容

    import java.io.File;
    
    public class Main {
        public static void main(String[] args) {
            File dir = new File("exampleDir");
            if (dir.isDirectory()) {
                String[] files = dir.list();
                if (files != null) {
                    for (String file : files) {
                        System.out.println(file);
                    }
                }
            }
        }
    }
    

3. 网络编程
3.1 套接字编程
  • 概念:套接字是网络通信的基本单位,用于建立客户端和服务器之间的连接。
3.2 创建服务器
  • 示例
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
        public static void main(String[] args) {
            try (ServerSocket serverSocket = new ServerSocket(1234)) {
                System.out.println("Server is listening on port 1234");
                while (true) {
                    try (Socket socket = serverSocket.accept()) {
                        OutputStream output = socket.getOutputStream();
                        output.write("Hello, client!".getBytes());
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

3.3 创建客户端
  • 示例
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.Socket;
    
    public class Client {
        public static void main(String[] args) {
            try (Socket socket = new Socket("localhost", 1234)) {
                InputStream input = socket.getInputStream();
                byte[] buffer = new byte[1024];
                int bytesRead = input.read(buffer);
                System.out.println(new String(buffer, 0, bytesRead));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
4. JDBC 编程
4.1 JDBC 概述
  • JDBC(Java Database Connectivity):Java API,用于连接和操作数据库。
4.2 连接数据库
  • 加载驱动

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    
  • 建立连接

    String url = "jdbc:mysql://localhost:3306/mydatabase";
    String username = "root";
    String password = "password";
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        System.out.println("Connected to the database");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    

4.3 执行查询
  • 示例
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        String sql = "SELECT * FROM users";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
    
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String email = resultSet.getString("email");
            System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    

4.4 执行更新
  • 示例
    try (Connection connection = DriverManager.getConnection(url, username, password)) {
        String sql = "UPDATE users SET email = 'newemail@example.com' WHERE id = 1";
        Statement statement = connection.createStatement();
        int rowsUpdated = statement.executeUpdate(sql);
        if (rowsUpdated > 0) {
            System.out.println("An existing user was updated successfully!");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    

小结

  • 本课学习了 Java 的输入输出操作,包括文件读写和序列化。
  • 探讨了文件和目录的操作方法。
  • 介绍了网络编程的基本概念和套接字编程。
  • 学习了 JDBC 编程,包括数据库连接、查询和更新操作。
  • 20
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值