Java系列(47)——打印流

本文深入探讨Java中的打印流概念,包括字节打印流和字符打印流,并通过实例演示如何使用PrintWriter进行数据输出,从文件读取数据并显示在控制台,以及复制文本文件。文章覆盖打印流的特点及其在不同场景下的应用。

本系列博客汇总在这里:Java系列_汇总


一、简介

在这里插入图片描述
在这里插入图片描述

  1. 打印流:只做输出没有输入。
  2. 打印流分为字节打印流和字符打印流。
  3. PrintWriter:字符打印流。

特点

  1. 可以打印各种数据类型。
  2. 封装了字符输出流,还可以字符流和字节流的转换。
  3. 可以使用自动刷新,则只有在调用 println、printf 或 format 的其中一个方法时才可能完成此操作。
  4. 可以直接向文件中写数据。

二、范例:使用打印流向文件中打印数据

  • 示例
    public static void main(String[] args)
    {
    
    	PrintWriter pw = null;
    
    	try
    	{
    		pw = new PrintWriter("b.txt");
    		pw.print(true);
    		pw.print('c');
    		pw.print(new char[] { 'd', 'g', 'g' });
    		pw.print(123l);
    		pw.print(12f);
    		pw.print(1);
    		pw.print(45);
    		pw.println("张三");
    		pw.flush();
    	} catch (FileNotFoundException e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if(pw != null)
    		{
    			pw.close();
    		}
    	}
    }
    
    在这里插入图片描述

三、范例:从文件中读取数据并且打印在控制台

  • 示例
    public static void main(String[] args)
    {
    	//定义缓冲区输入流对象
    	BufferedReader br = null;
    	
    	PrintWriter pw = null;
    
    	try
    	{
    		br = new BufferedReader(new FileReader("a.txt"));
    		
    		//pw = new PrintWriter(System.out);
    		//设置自动刷新的打印流,就不需要flush了
    		pw = new PrintWriter(System.out,true);
    		String line = null;
    		while ((line = br.readLine()) != null)
    		{
    			pw.println(line);
    			//pw.flush();
    		}
    	} catch (Exception e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if (pw != null)
    		{
    			pw.close();
    		}
    		try
    		{
    			if (br != null)
    			{
    				br.close();
    			}
    
    		} catch (IOException e)
    		{
    			e.printStackTrace();
    		}
    	}
    }
    
    在这里插入图片描述

四、范例:使用打印流来复制文本文件

  • 示例
    public static void main(String[] args)
    {
    	BufferedReader br = null;
    	PrintWriter pw = null;
    	System.out.println();
    	try
    	{
    		br = new BufferedReader(new FileReader("a.txt"));
    		pw = new PrintWriter("c.txt");
    		String line = null;
    		while ((line = br.readLine()) != null)
    		{
    			pw.println(line);
    		}
    	} catch (Exception e)
    	{
    		e.printStackTrace();
    	} finally
    	{			
    		try
    		{
    			if (pw != null)
    			{
    				pw.close();
    			}
    			if (br != null)
    			{
    				br.close();
    			}
    
    		} catch (IOException e)
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    
    在这里插入图片描述

如有错误,欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值