底层流:FileReader, FileWriter, FileInputStream,FileOutputStream
高层流:BufferedReader,BufferedWriter,BufferedInputStream,BufferedOutputStream
高层流必须由底层流构建。
文件关闭顺序必须为先关高层流,再关底层流,否则将会导致高层流异常关闭。
贴一些代码:
功能为从本地test1.txt中读取内容显示在页面上,并写入本地test2.txt中。
<%@ page contentType="text/html;charset=gb2312" language="java" %> <%@ page import = "java.io.*" %> <HTML> <BODY bgcolor=yellow> <% int n = 0; File f1 = new File("C:/tomcat/ch3","test1.txt"); File f2 = new File("C:/tomcat/ch3","test2.txt"); FileInputStream in = new FileInputStream(f1); BufferedInputStream bufferin = new BufferedInputStream(in); byte b[] = new byte[1000]; String temp = ""; while((n=bufferin.read(b))!=-1){ temp = new String(b, 0, n); out.println(temp); } FileOutputStream o = new FileOutputStream(f2); BufferedOutputStream bufferout = new BufferedOutputStream(o); bufferout.write(b); bufferout.flush(); bufferout.close(); in.close(); bufferin.close();
o.close(); %> </BODY> </HTML>
<%@ page contentType="text/html;charset=gb2312" language="java" %> <%@ page import = "java.io.*" %> <HTML> <BODY bgcolor=yellow> <% try{ int n = 0; File f1 = new File("C:/tomcat/ch3","test1.txt"); File f2 = new File("C:/tomcat/ch3","test2.txt"); char b[] = new char[10000]; FileReader fr = new FileReader(f1); BufferedReader br = new BufferedReader(fr); br.read(b); out.println(b); FileWriter o = new FileWriter(f2); BufferedWriter bw = new BufferedWriter(o); o.write(b); fr.close(); br.close(); bw.close(); o.close(); } catch(IOException e){ out.println(e); } %> </BODY> </HTML>