Java基础入门:异常,IO,多线程,集合,网络编程,数据库操作和反射

一、异常处理

Java 提供了异常处理机制来管理程序中的错误和意外事件。

1. 异常类型

常见的异常类型包括:

  • RuntimeException:由 JVM 抛出的运行时异常。

    • NullPointerException(空指针异常)
    • ArrayIndexOutOfBoundsException(数组越界)
  • IOException:与输入输出操作相关的异常。

2. 处理异常

使用 try-catch 块来处理异常:

try {
    // 可能会抛出异常的代码块
} catch (ExceptionType1 e) { // 捕获特定类型的异常
    // 处理ExceptionType1异常
} catch (ExceptionType2 e) { // 捕获另一种异常
    // 处理ExceptionType2异常
} finally {
    // 不管是否抛出异常,都会执行的代码块(可选)
}
3. 自定义异常

可以自定义异常类:

class MyException extends Exception { // 继承自Exception或RuntimeException
    public String getMessage() {
        return "自定义错误信息";
    }
}

// 抛出异常:
throw new MyException();

// 捕获异常:
try {
    // 代码块
} catch (MyException e) {
    // 处理自定义异常
}

二、文件与IO操作

Java 提供了丰富的I/O 类库,用于处理输入输出操作。

1. 文件读取

使用 FileReaderBufferedReader 读取文本文件内容:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReading {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("test.txt");
        BufferedReader br = new BufferedReader(fr);

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
        fr.close();
    }
}
2. 文件写入

使用 FileWriter 写入内容到文件中:

import java.io.FileWriter;
import java.io.IOException;

public class FileWriting {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("output.txt");
        fw.write("Hello, World!"); // 写入字符串
        fw.close();
    }
}

三、多线程

Java 支持多线程,通过继承 Thread 类或实现 Runnable 接口来创建线程。

1. 使用 Thread 类
class MyThread extends Thread {
    public void run() {
        System.out.println("子线程正在运行");
    }
}

public class Main {
    public static void main(String[] args) {
        // 创建并启动线程
        MyThread t = new MyThread();
        t.start(); // 调用start()方法启动线程

        System.out.println("主线程继续执行");
    }
}
2. 使用 Runnable 接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("子线程正在运行(通过Runnable)");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();
        Thread t = new Thread(mr);
        t.start();
    }
}

四、集合框架

Java 的集合框架提供了一种方法来处理一组对象。

1. 常用接口与类
  • List:有序的元素集合。

    • ArrayList:动态数组,支持随机访问和高效添加。
    • LinkedList:双向链表,支持快速插入和删除。
  • Set:不允许重复元素的集合。

  • Map:存储键值对。

2. 示例代码
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add(0, "Orange"); // 在索引0插入元素

        System.out.println(list.get(1)); // 输出Banana
        System.out.println(list.size()); // 输出3

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

五、网络编程

Java 提供了 SocketServerSocket 类来进行网络通信。

1. 基本结构
  • 客户端代码:

    import java.io.IOException;
    import java.net.Socket;
    
    public class Client {
        public static void main(String[] args) throws IOException {
            Socket socket = new Socket("localhost", 8080); // 连接本地服务器,端口号8080
            System.out.println("客户端已连接到服务器");
            socket.close();
        }
    }
    
  • 服务端代码:

    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class Server {
        public static void main(String[] args) throws IOException {
            ServerSocket server = new ServerSocket(8080); // 监听8080端口
            System.out.println("服务器已启动,等待客户端连接...");
          
            Socket socket = server.accept(); // 等待并接受连接
            System.out.println("有新客户端连接");
            socket.close();
            server.close();
        }
    }
    

六、数据库操作

Java 可以通过 JDBC(Java Database Connectivity)连接和操作数据库。

1. 基本步骤
  1. 加载驱动:

    String driver = "com.mysql.jdbc.Driver";
    Class.forName(driver);
    
  2. 连接数据库:

    String url = "jdbc:mysql://localhost:3306/dbname";
    String user = "root";
    String password = "password";
    
    Connection conn = DriverManager.getConnection(url, user, password);
    
  3. 执行 SQL 语句:

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
    
    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
    
    // 关闭资源
    rs.close();
    stmt.close();
    conn.close();
    
2. 示例代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {
    public static void main(String[] args) {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "password";

        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");

            while (rs.next()) {
                System.out.println(rs.getString(1));
            }

            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

七、反射与注解

Java 的反射机制允许通过代码动态访问类的信息。

1. 使用ReflectionAPI

获取类的方法:

import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) {
        Class<?> clazz = User.class;
        Method[] methods = clazz.getDeclaredMethods();

        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }

    private static void printName() {
        System.out.println("Hello, Reflection!");
    }
}

class User {
    public String getName() { return null; }
}
2. 使用注解

创建自定义注解:

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target(elementType = AnnotationElement.ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "";
}

应用注解并使用反射访问:

@MyAnnotation("Test")
public class AnnotatedClass {
    public void annotatedMethod() {}
}

import java.lang.reflect.Method;
import java.util.Arrays;

public class AnnotationExample {
    public static void main(String[] args) {
        Class<?> clazz = AnnotatedClass.class;
        Method[] methods = clazz.getDeclaredMethods();

        for (Method method : methods) {
            MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
            if (annotation != null) {
                System.out.println(annotation.value());
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值