本帖最后由 paul1234 于 2018-4-3 23:00 编辑
1.复制文本文件的5种方式如下A:利用基本流一次读写一个字符 B:利用基本流一次读写一个字符数组 C:利用缓冲流一次读写一个字符 D:利用缓冲流一次读写一个字符数组 E:利用缓冲流的特有方法一次读写一个字符串
2.代码演示:package com.itheima; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;
public class CopyFileTest { public static void main(String[] args) throws IOException { //数据源:FileWriterDemo.java StringsrcFileName = "FileWriterDemo.java"; //目的地:Copy.java StringdestFileName = "Copy.java"; method1(srcFileName,destFileName); method2(srcFileName,destFileName); method3(srcFileName,destFileName); method4(srcFileName,destFileName); method5(srcFileName,destFileName); } //缓冲流一次读写一个字符串 public static void method5(StringsrcFileName,String destFileName) throwsIOException { //创建输入缓冲流对象 BufferedReaderbr = new BufferedReader(new FileReader(srcFileName)); //创建输出缓冲流对象 BufferedWriterbw = new BufferedWriter(new FileWriter(destFileName)); //一次读写一个字符串 Stringline; while((line=br.readLine())!=null){ bw.write(line); bw.newLine(); bw.flush(); } //释放资源 bw.close(); br.close(); } //缓冲流一次读写一个字符数组 public static void method4(StringsrcFileName,String destFileName) throwsIOException { //创建输入缓冲流对象 BufferedReaderbr = new BufferedReader(new FileReader(srcFileName)); //创建输出缓冲流对象 BufferedWriterbw = new BufferedWriter(new FileWriter(destFileName)); //一次读写一个字符数组 char[] chs = newchar[1024]; int len; while((len=br.read(chs))!=-1) { bw.write(chs,0,len); } //释放资源 bw.close(); br.close(); } //缓冲流一次读写一个字符 public static void method3(String srcFileName,String destFileName) throws IOException { //创建输入缓冲流对象 BufferedReaderbr = new BufferedReader(new FileReader(srcFileName)); //创建输出缓冲流对象 BufferedWriterbw = new BufferedWriter(new FileWriter(destFileName)); //一次读写一个字符 int ch; while((ch=br.read())!=-1) { bw.write(ch); } //释放资源 bw.close(); br.close(); } //基本流一次读写一个字符数组 public static void method2(StringsrcFileName,String destFileName) throwsIOException { //创建输入流对象 FileReaderfr = new FileReader(srcFileName); //创建输出流对象 FileWriterfw = new FileWriter(destFileName); //一次读写一个字符数组 char[] chs = newchar[1024]; int len; while((len=fr.read(chs))!=-1) { fw.write(chs,0,len); } //释放资源 fw.close(); fr.close(); } //基本流一次读写一个字符 public static void method1(StringsrcFileName,String destFileName) throwsIOException { //创建输入流对象 FileReaderfr = new FileReader(srcFileName); //创建输出流对象 FileWriterfw = new FileWriter(destFileName); //一次读写一个字符 int ch; while((ch=fr.read())!=-1) { fw.write(ch); } //释放资源 fw.close(); fr.close(); } }
|