Java InputStreamReader read()方法
java.io.InputStreamReader.read() 方法读取并返回一个单个字符。
1 语法
public int read()
2 参数
无
3 返回值
该方法返回读取的字符,如果已到达流的末尾,则返回-1。
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.io.InputStreamReader.read()方法的例子
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Demo {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
InputStreamReader isr = null;
char c;
int i;
try {
// new input stream reader is created
fis = new FileInputStream("d:/test.txt");
isr = new InputStreamReader(fis);
// read till the end of the file
while((i = isr.read())!=-1) {
// int to character
c = (char)i;
// print char
System.out.println("Character Read: "+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
输出结果为:
Character Read: A
Character Read: B
Character Read: C
Character Read: D
Character Read: E
热门文章
优秀文章