Java InputStreamReader read()方法

java.io.InputStreamReader.read(char[] cbuf, int offset, int length) 方法读取字符到一个数组中的一个部分。

1 语法

public int read(char[] cbuf, int offset, int length)

2 参数

cbuf:目标字符缓冲区。

offset:偏移量开始存储字符的位置

length:要读取的字符数上限值

3 返回值

该方法返回读取的字符数,如果已到达流的末尾,则返回-1。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.InputStreamReader.read(char[] cbuf, int offset, int length)方法的例子
 */
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Demo{

        public static void main(String[] args) throws IOException {
            InputStreamReader isr = null;
            FileInputStream fis = null;
            char[] cbuf = new char[5];
            int i;

            try {
                // new input stream reader is created
                fis = new FileInputStream("d:/test.txt");
                isr = new InputStreamReader(fis);

                // reads into the char buffer
                i = isr.read(cbuf, 2, 3);

                // prints the number of characters
                System.out.println("Number of characters read: "+i);

                // for each character in the character buffer
                for(char c:cbuf) {

                    // for empty character
                    if(((int)c) == 0)
                        c = '-';

                    // prints the characters
                    System.out.println(c);
                }

            } catch (Exception e) {
                // print error
                e.printStackTrace();
            } finally {
                // closes the stream and releases resources associated
                if(fis!=null)
                    fis.close();
                if(isr!=null)
                    isr.close();
            }
        }
}

假设test.txt内容如下:

ABCDE

输出结果为:

Number of characters read: 3
-
-
A
B
C

热门文章

优秀文章