读写二进制文件

来源:互联网 发布:淘宝网天猫打底衫 编辑:程序博客网 时间:2024/04/29 19:19
import java.io._import java.nio._def writeInts(out:OutputStream, a:Array[Int], buf:ByteBuffer, n: Int) {    var nwritten = 0;    val ibuff = buf.asIntBufferval bbuff = buf.arraywhile (nwritten < n) {val todo = if (n-nwritten > ibuff.capacity) ibuff.capacity else (n - nwritten)ibuff.put(a, nwritten, todo)ibuff.position(0)out.write(bbuff,0,todo*4)nwritten += todo}}def writeFloats(out:OutputStream, a:Array[Float], buf:ByteBuffer, n:Int) {var nwritten = 0val fbuff = buf.asFloatBufferval bbuff = buf.arraywhile (nwritten < n) {val todo = if (n - nwritten > fbuff.capacity) fbuff.capacity else (n - nwritten)fbuff.put(a, nwritten, todo)fbuff.position(0)out.write(bbuff, 0, todo*4)nwritten += todo}}def writeDoubles(out:OutputStream, a:Array[Double], buf:ByteBuffer, n:Int) {var nwritten = 0val dbuff = buf.asDoubleBufferval bbuff = buf.arraywhile (nwritten < n) {val todo = if (n - nwritten > dbuff.capacity) dbuff.capacity else n - nwrittendbuff.put(a, nwritten, todo)dbuff.position(0)out.write(bbuff, 0, 8*todo)nwritten += todo}}//read n ints to a, buf is a buffer//instream --> buffer --> Arraydef readInts(in:InoutStream, a:Array[Int], buf:ByteBuffer, n:Int) {val nread = 0//a has read ints from buffval ibuff = buf.asIntBufferval bbuff = buf.arrayvar readnow = 0// buf has read n bytes from instreamwhile (nread < n) {val todo = if (n - nread > ibuff.capacity) ibuff.capacity else (n - nread) //for instants, need read 5 ints, 20 bytes, but buff only  has 18 bytes, so first time only read 16 bytes readnow += in.read(bbuff, readnow, todo*4 - readnow) //last time 'readnow' bytes hasnt put in array, but remain in the head of buffibuff.get(a, nread, readnow/4) //put and convert bytes in to ints to arrayibuff.position(0) //get will get bytes from positionnread += readnow/4if (readnow %4 ! =0) {System.arraycopy(bbuff, 4*(readnow/4), bbuff, 0, readnow%4)}readnow = readnow%4}}def writeBin() {val bos = new BufferedOutputStream(new FileOutputStream("tsmat"), 1024)val head  = new Array[Int](4)val tbuf = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN)val rows = 4val cols = 5val nnz = 8head(0) = 231head(1) = rowshead(2) = colshead(3) = nnz //nnzwriteInts(bos, head, tbuf, 4)val buff = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN)val colv = Array(0,1,2,4,6,8)val rowv = Array(2,1,1,2,2,3,0,2)val data = Array(0.3826f,0.5757f,0.2343f,0.4599f,0.5948f,0.6836f,0.49744f,0.92241f)writeInts(bos, colv, buff,cols+1)writeInts(bos, rowv, buff, nnz)writeFloats(bos, data, buff, nnz)bos.close}def readBin() {val bis = new BufferedInputStream(new FileInputStream("s45.1"), 1024)val buff = ByteBuffer.allocate(1024).order(ByteOrder.LITTLE_ENDIAN)val bbuff = buff.arrayval len = bis.read(bbuff,0,1024)println("len = " + len)for (i<-1 to 17) print(buff.getInt + " ")for (i<-1 to (len/4-17)) print(buff.getFloat + " ")bis.close}writeBin

0 0