Reader与Writer类
这两个类也是抽象类,都是字符操作类。
例1:向文件中写入一个字符串
import java.io.*;
public class ooDemo06 { public static void main(String[] args){ //1.新建一个File类,找到要操作的文件 File f = new File("E://gzg.txt"); //2.新建一个父类Writer类,并通过子类实例化 Writer out = null; try { out = new FileWriter(f); } catch (IOException e) { e.printStackTrace(); } //3. 向文件中写入数据 String str = "我爱你中国,亲爱的母亲。。。"; try { out.write(str); } catch (IOException e) { e.printStackTrace(); } //4.关闭写入流 try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } |
例2.从文件中读取数据,并打印输出到屏幕上。
import java.io.*;
public class ooDemo07 { public static void main(String[] args){ //1.使用File类找到要从中读取数据的文件 File f = new File("E://gzg.txt"); //2.新建一个Reader父类对象,并通过其子类 FileReader对象实例化 Reader in = null; try { in = new FileReader(f); } catch (FileNotFoundException e) { e.printStackTrace(); } //3.从文件中读取数据,并打印输出到屏幕上 int len = 0; char[] c = new char[1024]; try { len = in.read(c); } catch (IOException e) { e.printStackTrace(); } System.out.println("从文件中读取到的数据是:" + new String(c,0,len)); //4.close the inputstream try { in.close(); } catch (IOException e) {
e.printStackTrace(); } } }
|