Java写入的常用技巧(二)

在一般从流接收数据写入介质的场景中,大部分存在每批次数据较小,导致小文件较多的问题.

一般考虑设置一个缓冲池,将多个批次的数据先缓冲进去,达到一定大小,再一次性批量写入

//公共缓冲池和缓冲池大小,如果并发情况下,需要考虑加锁
//符合条件时就写入一次,否则数据只是写入缓冲池
private
static final int SIZE=10485760; private static final ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); public synchronized static void flush(String tableName, List<byte[]> bytes) { for (byte[] aByte : bytes) { try { byteBuffer.write(aByte); } catch (IOException e) { e.printStackTrace(); } } if (byteBuffer.size() >= SIZE) { //使用当前日期生成object key Date now = new Date(); String nowStr = dateFormat.format(now); doFlush(fileName, byteBuffer.toByteArray()); byteBuffer.reset(); } }

 对应的python版本

def put(filename, str):
    pass
if __name__=='__main__':
    str0 = ''
    for i in range(10000000):
        str0=str0+str
        if len(str0.encode())>10485760:
            put(i,str0)
            str0=''
原文地址:https://www.cnblogs.com/wangbin2188/p/11982454.html