MongoDB Java Driver 源码分析(12):GridFSFile、GridFSDBFile 和 GridFSInputFile

  GridFSFile 类表示 GridFS 中的文件的信息,它是一个抽象类,分别被 GridFSDBFile (表示从数据库中读取的文件) 和 GridFSInputFile(表示将要保存到数据库中的文件 ) 继承。

  GridFSFile 类包含下列属性(相应地有一系列的 get 方法)
[code]
Object _id; // 文件的唯一标识
String _filename; // 文件的名称
String _contentType; // 文件内容类型
long _length; // 文件长度
long _chunkSize; // 文件分块大小
Date _uploadDate; // 更新时间
List<String> _aliases; // 别名
DBObject _extradata = new BasicDBObject(); //额外信息
String _md5; // md5 值
[/code]
  此外它还提供保存文件信息的 save 方法:
[code]
// 保存文件
public void save(){
if ( _fs == null )
throw new MongoException( "need _fs" );
_fs._filesCollection.save( this );
}
[/code]
[size=medium][align=center][b]GridFSDBFile (从数据库中读取的文件)[/b][/align][/size]
  【将文件写入输出流】

  GridFSDBFile 的 writeTo 方法可以将文件写入输出流,以达到读取文件数据的目的。
[code]
// 将文件写入输出流
public long writeTo( OutputStream out )
throws IOException {
final int nc = numChunks();

// 遍历文件块,一次写入到输出流中
for ( int i=0; i<nc; i++ ){
out.write( getChunk( i ) );
}
return _length;
}

// 获取特定的文件块
byte[] getChunk( int i ){
if ( _fs == null )
throw new RuntimeException( "no gridfs!" );

// 调用 GridFS 的 _chunkCollection 的 findOne 方法
// _chunkCollection 中存放了文件数据
// 查询时指定了参数 files_id (文件的唯一标识) 和 n (序号)
DBObject chunk = _fs._chunkCollection.findOne( BasicDBObjectBuilder.start( "files_id" , _id ).add( "n" , i ).get() );
if ( chunk == null )
throw new MongoException( "can't find a chunk! file id: " + _id + " chunk: " + i );

// 获取文件块数据
return (byte[])chunk.get( "data" );
}
[/code]

  【获取输入流】

  另一种读取数据的方式是直接获取输入流。

[code]
// 获取输入流,用于读取数据
public InputStream getInputStream(){
return new MyInputStream();
}
[/code]
GridFSFile.MyInputStream 的 read 方法实现如下:
[code]
// 读取数据
// b 存放数据的字节数组
// off 偏移量
// len 长度
public int read(byte[] b, int off, int len){
// 偏移量超过文件大小
if ( _data == null || _offset >= _data.length ){
// 已经读完
if ( _nextChunk >= _numChunks )
return -1;

// 读取一块数据,以备使用
_data = getChunk( _nextChunk );
_offset = 0;
_nextChunk++;
}

// r:将要读取的数据的长度
int r = Math.min( len , _data.length - _offset );

// 将 _data 中指定偏移量和长度的数据复制到 b 中
System.arraycopy( _data , _offset , b , off , r );

// 增加偏移量
// 在 MyInputStream 内部记录当前的数据块读取到哪里了
// 下次再从这里开始读取
_offset += r;

// 返回读取的长度
return r;
}
[/code]

  【删除操作】

  GridFSDBFile 还提供从 GridFS 中删除文件的方法,实际上相当于调用 GridFS 的 remove 方法。
[code]
// 从 GridFS 的 _filesCollection 和 _chunkCollection 中删除文件
// 与 GridFS.remove 方法的实现相似, 实际上相当于调用 _fs.remove(_id)
void remove(){
_fs._filesCollection.remove( new BasicDBObject( "_id" , _id ) );
_fs._chunkCollection.remove( new BasicDBObject( "files_id" , _id ) );
}
[/code]
[size=medium][align=center][b]GridFSInputFile 准备写入数据库的文件[/b][/align][/size]
  GridFSInputFile 可以获得输出流,从而写入需要保存的数据,写入完毕后通过 close 方法提交修改。
[code]
// 获取输出流
public OutputStream getOutputStream() {
if ( _outputStream == null ) {
_outputStream = new MyOutputStream();
}
return _outputStream;
}
[/code]

  GridFSInputFile.MyOutputStream 的 write 方法的实现如下:
[code]
public void write( byte[] b , int off , int len ) throws IOException {
int offset = off;
int length = len;
int toCopy = 0;
while ( length > 0 ) {
// 计算每次需要写入的长度
toCopy = length;
if ( toCopy > _chunkSize - _currentBufferPosition ) {
toCopy = (int) _chunkSize - _currentBufferPosition;
}

// 复制数据
System.arraycopy( b, offset, _buffer, _currentBufferPosition, toCopy );

// 修改偏移量
_currentBufferPosition += toCopy;
offset += toCopy;
length -= toCopy;

// 已经到达文件块的结尾,写入数据库
if ( _currentBufferPosition == _chunkSize ) {
_dumpBuffer( false );
}
}
}

// 将缓冲区中的数据写入数据库中
// writePartial 为 true 表示不写入整块的数据,这通常用于写入文件数据的结尾部分。
private void _dumpBuffer( boolean writePartial ) {
if ( ( _currentBufferPosition < _chunkSize ) && !writePartial ) {
// 文件块不完整,返回
return;
}
if (_currentBufferPosition == 0) {
// 块为空,返回
return;
}

// 复制数据
byte[] writeBuffer = _buffer;
if ( _currentBufferPosition != _chunkSize ) {
writeBuffer = new byte[_currentBufferPosition];
System.arraycopy( _buffer, 0, writeBuffer, 0, _currentBufferPosition );
}

// 保存文件数据到数据库
DBObject chunk = BasicDBObjectBuilder.start()
.add( "files_id", _id )
.add( "n", _currentChunkNumber )
.add( "data", writeBuffer ).get();
_fs._chunkCollection.save( chunk );

// 改变偏移量等收尾工作
_currentChunkNumber++;
_totalBytes += writeBuffer.length;
_messageDigester.update( writeBuffer );
_currentBufferPosition = 0;
}
[/code]
  需要特别注意的是以下语句:
[code]
// 保存文件数据到数据库
DBObject chunk = BasicDBObjectBuilder.start()
.add( "files_id", _id )
.add( "n", _currentChunkNumber )
.add( "data", writeBuffer ).get();
_fs._chunkCollection.save( chunk );
[/code]
  借助 DBCollection.save 保存了数据。构造的 DBObject 包含三个属性:files_id (文件标识)、n(文件块序号)和 data(文件数据)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值