/**
* 将文件转化成二进制并给FileBody(BLOB)赋值
*/
@Override
public void select(String filename) {
// TODO Auto-generated method stub
getConnection();
sql = "select filebody from filelist where filename=? for update";
File file = new File(filename);
int flength = (int) file.length();
FileInputStream fis=null;
byte b[]=new byte[flength];
int itotal=0;
try {
fis = new FileInputStream(file);
//读取字节
for (int i = 0; itotal < flength; itotal=i+itotal) {
i=fis.read(b,itotal,flength-itotal);
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
opst=(OraclePreparedStatement) conn.prepareStatement(sql);
opst.setString(1, file.getName());
ors=(OracleResultSet) opst.executeQuery();
if (ors.next()) {
oracle.sql.BLOB blob=(BLOB) ors.getBlob(1);
int j=blob.putBytes(1, b);//转化成blob类型
System.out.println("j="+j);
conn.commit();//提交数据
ors.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取二进制转化成字节并学入指定文件夹中
*/
@Override
public void upload(String filename) {
// TODO Auto-generated method stub
getConnection();
sql = "select filebody from filelist where filename=? for update";
File file = new File(filename);
int flength = (int) file.length();
FileInputStream fis=null;
byte b[]=null;
try {
opst=(OraclePreparedStatement) conn.prepareStatement(sql);
opst.setString(1, file.getName());
ors=(OracleResultSet) opst.executeQuery();
if (ors.next()) {
oracle.sql.BLOB blob=(BLOB) ors.getBlob(1);//读取blob
int length=(int) blob.length();
System.out.println("j="+length);
b=blob.getBytes(1, length);//转化成byte
System.out.println("length="+length);
conn.commit();
ors.close();
}
//读取的字节内容保存到相应的文件夹中
FileUtil fileUtil =new FileUtil();
System.out.println("file---------------------------"+file.getName());
fileUtil.saveToFile(b,"E:\\files\\"+file.getName());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}