字符流习题
package com.day17.wd;import java.awt.Frame;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class LearnTest { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub method_02(); } //题目一:将一个.java文件打印到控制台上 public static void method_01(){ FileReader fr=null; try { fr=new FileReader("d.java"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } char[] s=new char[1024]; int num=0; try { while((num=fr.read(s))!=-1){ System.out.println(new String(s,0,num)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //题目二:将C盘一个文本文件复制到D盘 两种方法 /*步骤: * 1.在D盘创建一个文件,用于存储c盘文件中的数据 * 2.定义读取流和C盘文件关联 * 3.通过不断的读写完成数据存储 * 4.关闭资源 * */ //1.方法一,每次读取一个字符 public static void method_02()throws IOException{ FileWriter fw=new FileWriter("LearnTest_copy.txt"); FileReader fr=new FileReader("LearnTest.java"); int num=0; while ((num=fr.read())!=-1) { fw.write(num); } fw.close(); fr.close(); } //1.方法二,每一读取一个字符数组 public static void method_03(){ FileReader fr=null; FileWriter fw=null; try { fw=new FileWriter("LearnTest_copy.txt"); fr=new FileReader("LearnTest.java"); char[] ch=new char[1024]; int num=0; while((num=fr.read(ch))!=-1){ fw.write(ch, 0, num); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(fr!=null) fr.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }; try { if(fw!=null) fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}
TAG: