IO流--拷贝文本文件
2015-12-02 07:50
260 查看
//将文本文件复制到当前目录。 /* 流式: 复制原理: 其实就是将文件数据存储到当前目录的一个文件中。 步骤: 1.在当前目录创建一个同名文件,用于存储文件中的数据。 2.定义读取流和原文件关联。 3.通过不断的读写完成数据存储。 4.关闭资源。 */ import java.io.*; class CopyText { public static void main(String[] args) { copy_1(); copy_2(); } //读一个字符,就写一个字符。 public static void copy_1(){ FileWriter fw = null; FileReader fr = null; try{ //创建目的地 fw = new FileWriter("RuntimeDemo_copy.java"); //与已有文件关联 fr = new FileReader("RuntimeDemo.java"); int ch = 0; while((ch = fr.read()) != -1){ fw.write(ch); } } catch (IOException e){ throw new RuntimeException("读写失败!"); }finally{ try{ if(fr != null) fr.close(); }catch (IOException e){ System.out.println(e.toString()); } try{ if(fw != null) fw.close(); }catch (IOException e){ System.out.println(e.toString()); } } } //读完一块写。 public static void copy_2(){ FileWriter fw = null; FileReader fr = null; try{ //创建目的地 fw = new FileWriter("RuntimeDemo_copy.java"); //与已有文件关联 fr = new FileReader("RuntimeDemo.java"); char[] buffer = new char[1024]; int length = 0; while((length = read(buffer)) != -1){ fw.write(buffer,0,length); } }catch (IOException e){ throw new RuntimeException("读写失败!"); }finally{ try{ if(fr != null) fr.close(); }catch (IOException e){ System.out.println(e.toString()); } try{ if(fw != null) fw.close(); }catch (IOException e){ System.out.println(e.toString()); } } } } /*-----------------------------------------------------------------*/ /* 通过缓冲区复制一个.java文件。 readLine()方法返回的时候只返回回车符之前的数据内容,并不返回回车符。 */ import java.io.*; class CopyText { public static void main(String[] args) { copy_1(); } //读一个字符,就写一个字符。 public static void copy_1(){ BufferedReader br = null; BufferedWriter bw = null; try{ //创建缓冲区 br = new BufferedReader(new FileReader("RuntimeDemo.java")); bw = new BufferedWriter(new FileWriter("RuntimeDemo.java")); String line = null; while((line = br.readLine()) != null){ bw.write(line); bw.newLine(); bw.flush(); } }catch (IOException e){ throw new RuntimeException("读写失败!"); }finally { try{ if(br != null) br.close(); }catch (IOException e){ System.out.println(e.toString()); }try{ if(bw != null) bw.close(); }catch (IOException e){ System.out.println(e.toString()); } } } }
相关文章推荐
- Quartz.NET开源作业调度框架系列(二):CronTrigger
- 利用webview加载帧动画
- android CheckBox使用和状态获得
- 品读经典之温伯格
- GoldenGate for win安装配置
- 【cocos2d-x 3D游戏开发】1: 2D基础回顾---触摸事件(2.x)
- Unicode编码完全探究
- 通过命令模式搭建一个UI框架
- 简谈微信公众服务号的客服接口
- hive参数调节
- SparkSqlForTest
- Java代理系列-静态代理
- CSS里的各种水平垂直居中基础写法心得
- 通过百度API回放经纬度记录的信息(DEMO)
- 什么是特征向量,特征值,矩阵分解
- OSChina 周三乱弹 —— 围观最美代码
- Elasticsearch Cheat Sheet
- hive-列转行和行转列
- manjaro中okular中的pdf文件无法显示中文
- hive中order by,sort by, distribute by, cluster by作用以及用法