Java DataOutputStream size()方法

java.io.DataOutputStream.size() 用于返回写入数据输出流的字节数。

1 语法

public final int size()

2 参数

3 返回值

返回写入的计数器的最后一个值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.DataOutputStream.size()方法的例子
 */
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = null;
        DataOutputStream dos = null;
        byte[] buf = {87,64,72,31,90};

        try {
            // create file output stream
            fos = new FileOutputStream("d:/test.txt");

            // create data output stream
            dos = new DataOutputStream(fos);

            int size = 0;

            // for each byte in the buffer
            for (byte b:buf) {
                dos.write(b);

                // current value of the counter written
                size = dos.size();

                // print
                System.out.print("Size: "+size + "; ");
            }

        } catch(Exception e) {
            // if any error occurs
            e.printStackTrace();
        } finally {
            // releases all system resources from the streams
            if(fos!=null)
                fos.close();
            if(dos!=null)
                dos.close();
        }
    }
}

输出结果为:

Size: 1; Size: 2; Size: 3; Size: 4; Size: 5; 

热门文章

优秀文章