java io (四) Reader Writer

本文介绍了Java中字符流的基本用法,包括如何使用Writer类向文件中写入字符串,以及如何利用Reader类从文件中读取数据并输出到屏幕。通过两个具体的示例展示了基本的操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ReaderWriter

这两个类也是抽象类,都是字符操作类。

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();

   }

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值