“流屏蔽了实际的I/O设备中处理数据的细节”
输出流
对于InputStream和Reader而言,它们把输入设备抽象成一个“水管”,这个水管里的每个“水滴”依次排列。从上图可以看出,字节流和字符流的处理方式非常相似,只是它们处理的最小输入/输出单位不同而已。输入流使用隐式的记录指针来表示当前正准备从哪个“水滴”开始读取,每当程序从InputStream或Reader里取出一个或多个“水滴”后,记录指针自动向后移动。
对于OutputStream和Writer而言,它们同样把输出设备抽象成一个“水管”,只是这个水管里没有任何水滴。当我们执行输出时,程序相当于依次把“水滴”放入到输出流的水管中,输出流同样采用隐式的记录指针来标识当前水滴即将放入的位置,每当程序向OutputStream或Writer里输出一个或多个“水滴”后,记录指针自动向后移动
public class FileReaderTest{
public static void main(String args[]) {
FileReaderfr = null;
try {
fr = new FileReader("myFile.txt");
char[] cbuf = new char[32];
inthasRead =0;
while ((hasRead = fr.read(cbuf)) > 0 ) {
System.out.print(new String(cbuf, 0, hasRead));
}
}
catch (IOExceptionioe) {
ioe.printStackTrace();
}
finally{
if( fr != null) {
try {
fr.close();
}
catch (IOExceptionioe) {
ioe.printStackTrace();
}
}
}
}
}
public class FileOutputStreamTest {
public static void main(String args[]){
FileInputStreamfis = null;
FileOutputStreamfos = null;
try {
fis = new FileInputStream("myFile.txt");
fos = new FileOutputStream("nextFile.txt");
byte[] bbuf = new byte[32];
inthasRead =0;
while ((hasRead = fis.read(bbuf)) > 0 ) {
fos.write(bbuf, 0, hasRead);
}
}
catch (IOExceptionioe) {
ioe.printStackTrace();
}
finally {
if( fis != null) {
try {
fis.close();
}
catch(IOExceptionioe) {
ioe.printStackTrace();
}
}
if( fos != null) {
try {
fos.close();
}
catch(IOExceptionioe) {
ioe.printStackTrace();
}
}
}
}
}
练习 1
请问以下哪些是定义在java.io包中的抽象类(不定选题)
A. InputStream
B. PrintStream
C. Reader
D. FileInputStream
E. FileWriterpublic class KeyinTest {
public static void main(String args[]){
BufferedReaderbr = null;
try {
InputStreamReader reader = new InputStreamReader(System.in);
br = new BufferedReader(reader);
String buffer = null;
while ((buffer = br.readLine()) != null) {
System.out.println(“输入内容为:”+ buffer);
}
}
catch (IOExceptionioe) {
ioe.printStackTrace();
}
finally {
if( br != null) {
br.close();
}
}
}
}
用一行表达式实现:
BufferedReaderstdin = new BufferedReader ( new InputStreamReader(System.in) );
Note:当我们使用处理流来包装底层节点流之后,关闭输入/输出流资源时,只要关闭最上层的处理流即可。关闭最上层的处理流时,系统会自动关闭被该处理流包装的节点流。
public class RedirectOut {
public static void main(String[] args){
PrintStreamps = null;
try {
ps = new PrintStream(new FileOutputStream("out.txt"));
System.setOut(ps);
System.out.println("普通字符串");
System.out.println(new RedirectOut());
}
catch(IOExceptionioe) {
ioe.printStackTrace();
}
finally{
if(ps != null){
ps.close();
}
}
}
}