Java DataInputStream read()方法

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

1 语法

public final int read(byte[] b)

2 参数

b:从此流中读取数据的缓冲区数组。

3 返回值

流中的字节总数,如果流已到达末尾,则为-1。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.DataInputStream.read(byte[] b)方法的例子
 */
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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 input stream from file input stream
            is = new FileInputStream("d:\\test.txt");

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

            // count the available bytes form the input stream
            int count = is.available();

            // create buffer
            byte[] bs = new byte[count];

            // read data into buffer
            dis.read(bs);

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

                // convert byte into character
                char c = (char)b;

                // print the character
                System.out.print(c+" ");
            }

        } catch(Exception e) {
            // if any I/O error occurs
            e.printStackTrace();
        } finally {
            // releases any associated system files with this stream
            if(is!=null)
                is.close();
            if(dis!=null)
                dis.close();
        }
    }
}

输出结果为:

￿ ￾ A   B   C   D   E   

热门文章

优秀文章