IO(字符流——复制文本文件)
方法一
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Created by Mr.Li on 2017/6/1. */ //需求:将f盘的一个文本文件复制到d盘。 /* 1;需要读取源 2:将读到的数据写入目的地 3:既然是操作文本文件,使用字符流 */ public class CopyTextTest { public static void main(String []args)throws IOException { //1,读取一个已有的文本文件没使用字符读取流和文件相关联 FileReader fr=new FileReader("hhh.txt"); //2创建一个目录,用于存储读到的数据 FileWriter fw=new FileWriter("nnn.txt"); //3:频繁的读学操作 int ch=0; while ((ch=fr.read())!=-1) { fw.write(ch); } //4:关闭流资源 fw.close(); fr.close(); } } //Exception in thread "main" java.io.FileNotFoundException: 000.txt (系统找不到指定的文件。) //因为这个文件必须建立在Java大文件中,否则读取不到
方法二
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * Created by Mr.Li on 2017/6/2. */ public class CopyTextTest1 { private static final int BUFFER_SIZE=1024; public static void main(String[] args) throws IOException { FileReader fr = null; FileWriter fw = null; try { fr = new FileReader("hhh.txt"); fw = new FileWriter("nnn.txt"); //创建一个临时容器,用于缓存读取到的字符。 char[] buf = new char[BUFFER_SIZE]; //定义一个变量记录读取到的字符(其实就是往数组里装的字符个数) int len = 0; while ((len = fr.read(buf)) != -1) { fw.write(buf, 0, len); } } catch (Exception e) { //System.out.println("读写失败"); throw new RuntimeException("读写失败"); } finally { if (fw != null) try { fw.close(); } catch (IOException e) { e.printStackTrace(); } if (fr != null) try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
就while语句循环次数来讲:方法2 效率更高