输入流:数据从数据源(文件)到程序(内存)的路径。
输出流:数据从程序(内存)到数据源(文件)的路径。
package file; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Reader01 { public static void main(String[] args) throws IOException { String filePath = "e:\\hello.txt"; FileReader fileReader = null; int readLen = 0; char[] buf = new char[8]; //一次读8个 try { fileReader = new FileReader(filePath); //循环读取,返回实际读取到的字符数,如果返回-1,代表文件结束 while((readLen = fileReader.read(buf))!= -1){ System.out.print(new String(buf,0,readLen)); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { fileReader.close(); } } // fileReader.write()可以写入 }
区别和联系:
节点流是底层流,直接和数据源相接。
处理流包装节点流,可以消除不同节点流的实现差异,提供跟方便的方法来完成输入输出。使用了修饰器设计模式,不会直接与数据源相连。
public class bufferReader01 { public static void main(String[] args) throws IOException { String filePath = "e:\\hello.txt"; BufferedReader bufferedReader = null; String line; bufferedReader = new BufferedReader(new FileReader(filePath)); while((line = bufferedReader.readLine())!= null){ System.out.println(line); } bufferedReader.close(); } }
public class bufferWriter01 { public static void main(String[] args) throws IOException { String filePath = "e:\\e.txt"; BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); bufferedWriter.write("hello,world1"); bufferedWriter.newLine(); //换行 bufferedWriter.write("hello,world2"); bufferedWriter.close(); } }