zoukankan      html  css  js  c++  java
  • io--文件内容的复制

     1 public class CopyTextTest_2 {
     2 
     3  private static final int BUFFER_SIZE = 1024;
     4  public static void main(String[] args) {
     5 
     6   FileReader fr = null;
     7   FileWriter fw = null;
     8   try {
     9    //创建字节输入流,选择要读取数据的文件
    10    fr = new FileReader("IO流_2.txt");
    11    //创建字节输出流,选择要写入数据的文件
    12    fw = new FileWriter("copytest_2.txt");
    13    
    14    //创建一个临时容器,用于缓存读取到的字符。
    15    char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。 
    16    
    17    //定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 )
    18    int len = 0;
    19    //循环从输入流中取出的数据
    20    while((len=fr.read(buf))!=-1){
    21   //每读取一次,即写入文件输入流,读多少写多少
    22     fw.write(buf, 0, len);
    23    }
    24    
    25   } catch (Exception e) {
    26 //   System.out.println("读写失败");
    27    throw new RuntimeException("读写失败");
    28   }finally{
    29    if(fw!=null)
    30     try {
    31      fw.close();
    32     } catch (IOException e) {
    33      
    34      e.printStackTrace();
    35     }
    36    if(fr!=null)
    37     try {
    38      fr.close();
    39     } catch (IOException e) {
    40      
    41      e.printStackTrace();
    42     }
    43   }
    44  }
    45 
    46 }

     使用缓冲流:

     1 public static void main(String[] args) {
     2         FileReader fr=null;
     3         FileWriter fw=null;
     4         BufferedReader br=null;
     5         BufferedWriter bw=null;
     6         try {
     7             fr=new FileReader("e://test.txt");
     8             fw=new FileWriter("e://newFile.txt");
     9             br=new BufferedReader(fr);
    10             bw=new BufferedWriter(fw);
    11             
    12             String line=null;
    13             while ((line=br.readLine())!=null) {
    14                 bw.write(line);
    15             }
    16         } catch (IOException e) {
    17             
    18             e.printStackTrace();
    19         }finally{
    20             try {
    21                 //要关闭缓冲流,这样数据才会被刷新然后写入到新的文件中
    22                 bw.close();
    23                 br.close();
    24             } catch (IOException e) {
    25                 
    26                 e.printStackTrace();
    27             }
    28         }
    29         
    30     }
    31                                                                                         
  • 相关阅读:
    MongoDB常用命令
    centos6.9下MongoDB安装
    第三十二节 selenium爬取拉勾网
    第三十节 selenium设置代理
    第三十节 selenium打开多个窗口和切换
    第二十九节 selenium隐式和显式等待
    第二十八节 selenium操作cookie信息
    第二十七节 selenium行为链
    第二十六节 selenium操作表单元素
    SpringMVC工作原理详解
  • 原文地址:https://www.cnblogs.com/fifiyong/p/6413048.html
Copyright © 2011-2022 走看看