第八章 流 03_FileReader_FileWriter

来源:互联网 发布:mac装双系统怎么切换 编辑:程序博客网 时间:2024/05/22 13:34

鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.1)


这一节没有什么就是FileReader 和FileWriter示例程序!

// TestFileReader.javaimport java.io.*;public class TestFileReader {public static void main(String args[]) {FileReader fr = null;int c = 0;try{fr = new FileReader("c:/java/IO/TestFileReader.java");  //注意反斜杠和斜杠和separator的区别while((c = fr.read()) != -1) {System.out.print((char)c);                      //错误用法 char(c);}fr.close();}catch (FileNotFoundException e){System.out.println("找不到文件");System.exit(-1);}catch (IOException e1) {System.out.println("数据读取错误");System.exit(-1);}}}

// TestFileWriter.javaimport java.io.*;public class TestFileWriter {public static void main(String args[]) {FileWriter fw = null;try{fw = new FileWriter("c:/java/IO/unicode.java");  //只能建文件,不能建目录for(int i = 0; i < 50000; i ++) {fw.write(i);}fw.close();}catch (FileNotFoundException e){System.out.println("文件不存在");System.exit(-1);}catch (IOException e1) {System.out.println("写入错误");System.exit(-1);}System.out.println("成功写入");}}


小作业就是用FileReader和FileWriter把一个文件复制到另一个文件


// SmallExe.java//自己写的import java.io.*;public class SmallExe {public static void main(String args[]) {int c = 0;FileReader fr = null;FileWriter fw = null;try{fr = new FileReader("c:/java/IO/TestFileInputStream.java");fw = new FileWriter("c:/java/IO/TFIS.java");while((c = fr.read()) != -1) {fw.write(c);}fr.close();fw.close();}catch (FileNotFoundException e){System.out.println("文件不存在");System.exit(-1);}catch(IOException e1) {System.out.println("读写错误");System.exit(-1);}System.out.println("文件已复制");}}


原创粉丝点击