下面是从数据库中取出blob数据写入到文件中去的操作。 import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; importjava.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class GetBlob { static { String driverName = "oracle.jdbc.driver.OracleDriver"; try { Class.forName(driverName); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() { Connection conn = null; String username = "*****"; String password = "*****"; String url = "jdbc:oracle:thin:@****:1521:****"; try { conn = DriverManager.getConnection(url, username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void saveBlob(Blob b) throws IOException, SQLException { System.out.println("blob=" + b); InputStream in = b.getBinaryStream(); // 建立输出流 // FileInputStream in =(FileInputStream)b.getBinaryStream(); FileOutputStream file = new FileOutputStream("d:\\多多.txt"); int len = (int) b.length(); byte[] buffer = new byte[len]; // 建立缓冲区 while ((len = in.read(buffer)) != -1) { file.write(buffer, 0, len); } file.close(); in.close(); } public static void main(String[] args) { Connection conn = getConnection(); Statement stmt = null; try { stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery("SELECT CONTENT FROM AT_FILEUPLOAD WHERE FILE_ID=6243"); if (rs.next()) { Blob blob = rs.getBlob("content"); // 把blob形式的内容存到文件中去 try { System.out.println("saveBlob"); saveBlob(blob); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
|