进阶day09-字符流的读取一个字符
This commit is contained in:
49
javaSE-day09/src/com/inmind/reader03/Demo10.java
Normal file
49
javaSE-day09/src/com/inmind/reader03/Demo10.java
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package com.inmind.reader03;
|
||||||
|
|
||||||
|
import java.io.FileNotFoundException;
|
||||||
|
import java.io.FileReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
/*
|
||||||
|
字符流的读取一个字符
|
||||||
|
在java中使用抽象类Reader表示字符输入流
|
||||||
|
常用子类FileReader
|
||||||
|
构造方法:
|
||||||
|
FileReader(File file) 创建一个新的 FileReader ,给出 File读取。
|
||||||
|
FileReader(String fileName) 创建一个新的 FileReader ,给定要读取的文件的名称。
|
||||||
|
|
||||||
|
常用方法:
|
||||||
|
abstract void close() 关闭资源
|
||||||
|
int read() 读一个字符,返回了读取到的字符数据
|
||||||
|
int read(char[] cbuf) 将字符读入数组。
|
||||||
|
|
||||||
|
使用步骤:
|
||||||
|
1.创建对象
|
||||||
|
2.调用读方法
|
||||||
|
3.释放资源
|
||||||
|
*/
|
||||||
|
public class Demo10 {
|
||||||
|
public static void main(String[] args) throws IOException {
|
||||||
|
FileReader fr = new FileReader("a.txt");
|
||||||
|
|
||||||
|
//读一个字符
|
||||||
|
/*int ch = fr.read();
|
||||||
|
System.out.println((char) ch);
|
||||||
|
|
||||||
|
ch = fr.read();
|
||||||
|
System.out.println((char) ch);//中
|
||||||
|
|
||||||
|
ch = fr.read();
|
||||||
|
System.out.println((char) ch);//国
|
||||||
|
|
||||||
|
ch = fr.read();
|
||||||
|
System.out.println( ch);//-1*/
|
||||||
|
|
||||||
|
int ch;//用来接收读取到的字符
|
||||||
|
while ((ch = fr.read()) != -1) {
|
||||||
|
System.out.print((char) ch);
|
||||||
|
}
|
||||||
|
|
||||||
|
fr.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user