Java DataInputStream readFully()方法

java.io.DataInputStream.readFully(byte[] b) 用于从输入流中读取字节并将其存储到缓冲区数组中。

1 语法

public final void readFully(byte[] b)

2 参数

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);

            // for each byte in the buffer
            for (byte b:buf) {

                // convert byte to char
                char 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内容如下:

ABCDE

输出结果为:

ABCDE

热门文章

优秀文章