第1个回答 2010-01-26
二进制文件 打开二进制文件的语法格式如下:
Open pathname For Binary As [#]filenumber
说明: (1) 参数filename 和filenumber 分别表示文件名或文件号. (2)关键字Binary 表示打开的是二进制文件 (3)对于二进制文件,不能指定字节长度.每个打开的二进制文件都有一个自己的指针,文件指针是一个数字值,指向下一次读写操作的文件中的位置.二进制文件中的每个”位置”对应一个数据字节,因此,有n个字节的文件,就有1到n个位置. 我们可以用Seek()函数返回当前的文件指针位置(即下一个要读写的字节 );用Loc()函数返回上一次读写的字节位置,除非用Seek语句移动了指针,Loc()返回值总比Seek()的小1.我们来看下面的例子:
Open “student.txt” for Binary as #1
该语句用二进制的方式打开了student.txt文件.
你试试看
第4个回答 推荐于2016-10-29
以下代码,在我的MySQL数据库中测试通过~
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* MySQL建表语句:create table test (id int primary key,xls blob)
*
*/
public class test {
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
test t = new test();
t.insertXLS2DB(new File("D:\\test.xls"));
t.readXLSFromDB(new File("D:\\test2.xls"));
}
public void insertXLS2DB(File file) throws Exception{
FileInputStream fis = null;
Connection con = null;
PreparedStatement ps = null;
try {
fis = new FileInputStream(file);
con = getConnection();
con.setAutoCommit(false);
ps = con.prepareStatement("insert into test values(?,?)");
ps.setInt(1, 3);
ps.setBinaryStream(2,fis,fis.available());
ps.executeUpdate();
con.commit();
} catch (Exception e) {
if(con!=null)
con.rollback();
throw e;
}finally{
releaseResource(fis,ps,con);
}
}
public void readXLSFromDB(File f) throws Exception{
InputStream is = null;
FileOutputStream fos = null;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = getConnection();
con.setAutoCommit(false);
ps = con.prepareStatement("select xls from test where id = ?");
ps.setInt(1, 3);
rs = ps.executeQuery();
if(!f.exists()){
f.createNewFile();
}
fos = new FileOutputStream(f);
while(rs.next()){
is = rs.getBinaryStream("xls");
}
con.commit();
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1){
fos.write(bytes, 0, len);
}
fos.flush();
}catch(Exception e){
if(con!=null)
con.rollback();
throw e;
}finally{
releaseResource(is,fos,ps,con);
}
}
public Connection getConnection() throws SQLException{
return DriverManager.getConnection("jdbc:mysql://localhost:3306/pm?useUnicode=true&characterEncoding=UTF-8","root","gg");
}
public void releaseResource(Object... objs) throws IOException, SQLException{
for(Object obj:objs){
if(obj!=null){
if(obj instanceof Closeable){
((Closeable) obj).close();
}else if(obj instanceof Connection){
((Connection) obj).close();
}else if(obj instanceof Statement){
((Statement) obj).close();
}
}
}
}
}本回答被提问者采纳