import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
public class ReaderDemo {
/**
* 使用字符流读取文本文件
*/
public static void stringReader(){
File f = new File("E:\\测试用例.txt");
try {
//构造一个字符输入流对象
Reader ri = new FileReader(f);
char[] cs = new char[20];
int len = -1;
StringBuffer sb = new StringBuffer();
while ((len = ri.read(cs))!=-1){
sb.append(new String(cs,0,len));
}
//关闭流
ri.close();
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用字节流读取文本文件
* @param args
*/
public static void byteReader(){
File f = new File("E:\\测试用例.txt");
try {
InputStream is = new FileInputStream(f);
byte[] bytes = new byte[1024];
int len = -1;
StringBuffer sb = new StringBuffer();
while ((len = is.read(bytes))!=-1){
sb.append(new String(bytes,0,len));
}
is.close();
System.out.println(sb);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//byteReader();
stringReader();
}
}
幕附
相关分类