数据库中有表定义如下:
CREATE TABLE USERFILE_TABLE(
ID SERIAL PRIMARY KEY,
NAME VARCHAR(256),
USERFILE BLOB);
程序代码如下:(使用的数据库是特殊数据库,所以要想使用本代码,请自行修改,主要改一下“注册JDBC”和“建立连接”部分)
import java.io.*;
public class OutputFile {
public OutputFile() {
}
public static void main(String[] args) throws SQLException {
try {
//注册神通数据库 JDBC驱动
Class.forName("com.oscar.Driver");
}catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
}
//与后台数据库建立连接
String user = "SYSDBA";
String name = "szoscar55";
String url = "jdbc:oscar://localhost/OSRDB";
Connection con = DriverManager.getConnection(url,user,name);
//查询
Statement stmt = con.createStatement();
ResultSet result_set = stmt.executeQuery(
"SELECT * FROM USERFILE_TABLE WHERE NAME='".concat(args[0]).concat("'"));
//输出多个文件时,用int file_name_index来区别不同的文件
Integer file_name_index = new Integer(0);
//int file_name_index = 0;
//输出文件流,用来保存文件
FileOutputStream file_output_stream = null;
//InputStream用来把数据库中的blob“输入”到buffer
InputStream input_stream = null;
try {
while (result_set.next()) {
String file_name = result_set.getString(2);
file_name = "Output/".concat(file_name);
//若Output目录不存在,则生成
File output_file_path = new File("Output");
if(!output_file_path.exists()){
output_file_path.mkdir();
}
//生成file_output_stream对象,文件名自动生成,当有重名时,文件名后加上数字 1 2 3...
if(0 == file_name_index){
file_output_stream = new FileOutputStream(file_name);
}
else{
//把文件名和扩展名分开
int extension_name_index = file_name.lastIndexOf('.');
//文件名
String file_name_without_extension_name = file_name.substring(0,extension_name_index-1);
//扩展名
String extension_name = file_name.substring(extension_name_index);
file_output_stream = new FileOutputStream(file_name_without_extension_name.concat(file_name_index.toString()).concat(extension_name));
}
//从查询的结果集中找出blob,由于结果是:ID NAME USERFILE,因此getBlob()的参数是 3
Blob blob_output = result_set.getBlob(3);
//把input_stream和blob_output绑定
input_stream = blob_output.getBinaryStream();
byte[] buffer = new byte[1024];
int length = 0;
while((length = input_stream.read(buffer)) >= 0){
//把buffer中的内容,一点点地写到文件中
file_output_stream.write(buffer,0,length);
}
file_output_stream.flush();//关闭文件
//输出多个文件时,用int file_name_index来区别不同的文件
file_name_index += 1;
}
}
catch (Exception e) {
String err = e.toString();
System.out.println(err);
}
finally {
//关闭流
try{
if(file_output_stream != null)
file_output_stream.close();
}
catch(IOException file_output_stream_exception){
System.out.println(file_output_stream_exception);
}
try{
if(input_stream != null)
input_stream.close();
}
catch(IOException input_stream_exception){
System.out.println(input_stream_exception);
}
}
result_set.close();
stmt.close();
con.close();
}
}
编译:
javac OutputFile.java
运行:
java OutputFile test.bmp