java字节流转换成字符流-

本文展示了如何在Java中将字节流转换为字符流。通过使用InputStreamReader和BufferedReader,可以将标准输入(字节流)转换为字符流进行处理,并将数据写入文件。同样,使用BufferedWriter可以将字符流转换回字节流并写入文件。

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

--------------------------------java字节流转换成字符流-------------------------------

 

InputStreamReader是字节流通向字符流的桥梁。

 

范例:把从键盘输入的文本写入到文件中

 

public class ScannerDemo {

 

    public static void main(String[] args) {

       

        //创建Scanner对象

        Scanner sc = new Scanner(System.in);

           BufferedWriter bw = null;

        try {

           bw = new  BufferedWriter(new FileWriter("c.txt"));

           String line = null;

           while((line = sc.nextLine()) != null) {

               //给出退出条件

               if("exit".equals(line)) {

                   break;

               }

               bw.write(line);

               bw.newLine();

               //释放缓冲区

               bw.flush();

           }

        } catch (IOException e) {

           e.printStackTrace();

        }finally {

          

           try {

               if(bw != null)

               bw.close();

           } catch (IOException e) {

               e.printStackTrace();

           }

        }

    }

   

}

 

 

=============================================================

 

范例:把字节流转换成字符流

public  class ConverterInDemo {

 

    public  static  void main(String[] args) {

       

        InputStream is = System.in;

        //要想使用字符流的高效缓冲区来操作字节流需要转换

        BufferedReader br = new  BufferedReader(new InputStreamReader(is));

        //定义要写入的文件流

        BufferedWriter bw = null;

        String line = null;

        try {

           bw = new  BufferedWriter(new FileWriter("b.txt"));

           while((line = br.readLine()) != null) {

               if("exit".equals(line))

                   break;

               bw.write(line);

               bw.newLine();

               bw.flush();

           }

        } catch (IOException e) {

           e.printStackTrace();

        }finally {

          

           try {

               if(br != null)

                 br.close();

               if(bw !=null)

                   bw.close();

           } catch (IOException e) {

               e.printStackTrace();

           }

        }

       

       

    }

   

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值