Java DataInputStream read()方法

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

1 语法

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

2 参数

b:从输入流中读取数据的byte[]。

off:b[]中的起始偏移量。

len:读取的最大字节数。

3 返回值

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

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.DataInputStream.read(byte[] b, int off, int len)方法的例子
 */
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 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 len data into buffer starting at off
            dis.read(bs, 4, 3);

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

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

                // empty byte as char '0'
                if(b == 0)
                    c = '0';

                // 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();
        }
    }
}

输出结果为:

0000￿￾A00000

热门文章

优秀文章