在Java編程中,經常需要導入和導出數據。這可能是從一個文件中讀取數據,將數據插入到數據庫中,或將數據從數據庫中導出為文件。以下是一些常見的導入和導出數據方法。
//從文件中讀取數據 try { File file = new File("data.txt"); Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { String data = scanner.nextLine(); System.out.println(data); } scanner.close(); } catch (FileNotFoundException e) { System.out.println("文件不存在。"); } //將數據插入到數據庫中 String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "username"; String password = "password"; try (Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement()) { String sql = "INSERT INTO mytable (name, age) VALUES ('John', 25)"; stmt.executeUpdate(sql); System.out.println("插入成功。"); } catch (SQLException e) { System.out.println(e.getMessage()); } //將數據從數據庫中導出為文件 try (Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement()) { String sql = "SELECT * FROM mytable"; ResultSet result = stmt.executeQuery(sql); FileWriter writer = new FileWriter("data.txt"); while (result.next()) { String name = result.getString("name"); int age = result.getInt("age"); writer.write(name + ", " + age + "\n"); } writer.close(); System.out.println("導出成功。"); } catch (SQLException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); }