字符流_复制文本文件_练习

需求:将F盘一个文本文件复制到E盘

复制原理:就是将F盘下的文件数据存储到E盘的一个文件中。连读带写

步骤:
  1.在E盘创建一个文件,用于存储F盘文件中的数据
  2.定义读取和F盘文件关联
  3.通过不断的读写完成数据存储
  4.关闭资源

 1 import java.io.FileReader;

 2 import java.io.FileWriter;

 3 import java.io.IOException;

 4 

 5 public class CopyDemo {

 6     public static void main(String[] args) throws IOException {

 7         copy();

 8     }

 9     

10     //从F盘读一个字符,就往E盘写一个字符

11     public static void copy()throws IOException{

12         //创建目的地

13         FileWriter fw = new FileWriter("E:\\java.txt");

14 

15         //与已有文件关联

16         FileReader fr = new FileReader("F:\\dmeo.txt");

17         

18         int ch = 0;

19         while ((ch = fr.read())!=-1){

20             fw.write(ch);

21         }

22         fw.close();

23         fr.close();

24     }

25 }

 

 上面的方法效率比较低,没有缓冲区,读一个字符写一个字符,可以使用下面的代码,定义缓冲区,提高效率

 1 import java.io.FileReader;

 2 import java.io.FileWriter;

 3 import java.io.IOException;

 4 

 5 public class CopyDemo {

 6     private static final int BUFFER_SIZE = 1024;

 7     

 8     public static void main(String[] args) throws IOException, RuntimeException {

 9         copy();

10     }

11     

12     public static void copy()throws IOException,RuntimeException{

13         FileReader fr = null;

14         FileWriter fw = null;

15         try{

16             fw = new FileWriter("java.txt");

17             fr = new FileReader("F:\\guangpan.txt");

18 

19             //char[] buf = new char[1024];

20             char[] buf = new char[BUFFER_SIZE];

21             int len = 0;

22             while ((len = fr.read(buf))!=-1){

23                 fw.write(buf,0,len);

24             }

25         }catch (IOException e){

26             throw new RuntimeException("读写失败");

27             

28         }finally{

29             if(fr!=null)

30                 try{

31                     fr.close();

32                 }catch (IOException e){

33                     

34                 }

35             if(fw!=null) {

36                 try {

37                     fw.close();

38                 } catch (Exception e2) {

39                     

40                 }

41             }

42                 

43         }

44 

45     }

46 }

 

你可能感兴趣的:(文本文件)