Java DataInputStream readFully()方法

java.io.DataInputStream.readFully(byte[] b) 用于从输入流中读取len个字节。

1 语法

public final void readFully(byte[] b, int off, int len)

2 参数

b:目标缓冲区。

off:数据的偏移量。

len:要读取的字节数。

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.DataInputStream.readFully(byte[] b) 方法的例子
 */
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws IOException {
        InputStream is = null;
        DataInputStream dis = null;

        try {
            // create file input stream
            is = new FileInputStream("d:\\test.txt");

            // create new data input stream
            dis = new DataInputStream(is);

            // available stream to be read
            int length = dis.available();

            // create buffer
            byte[] buf = new byte[length];

            // read the full data into the buffer
            dis.readFully(buf, 4, 5);

            // for each byte in the buffer
            for (byte b:buf) {
                char c = '0';
                if(b!=0)
                    c = (char)b;

                // prints character
                System.out.print(c);
            }

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

假设test.txt内容如下:

Hello World!

输出结果为:

0000Hello000

热门文章

优秀文章