I/O流之打印流

打印流,顾名思义,就是具有打印功能的流,可以打印任何类型的数据信息,比如小数,整数,字符串等...

打印流的本质只是对OutputStream类的功能做了一个封装而已,可以看作是OutputStream功能的加强版。

 打印流按照操作的数据类型可分为两类:

  1. 字节打印流  PrintStream
  2. 字符打印流  PrintWriter

打印流的继承结构:

                     

范例:使用打印流

public class Test {
    public static void main(String[] args) throws Exception {
     PrintWriter printwriter=new PrintWriter(new FileOutputStream(new File("C:/users/10320/ideaProjects/test.txt")));
      //将内容写入文件
      printwriter.print("hello word");
      printwriter.print(123456);
      printwriter.print(123.4);
      printwriter.print("加油!");
      printwriter.close();
    }
}

 格式化输出:在Java中也提供了类似于C语言printf()风格的格式化输出功能

  • PrintStream类的printf()方法
  • String类的format()方法

(1)格式化输出

public PrintStream printf(String format, Object ... args)

范例:格式化输出

public class Test {
    public static void main(String[] args) throws Exception {
        String name="rachel";
        int age=18;
        double salary=8000.00;
     PrintWriter printwriter=new PrintWriter(new FileOutputStream(new File("C:/users/10320/ideaProjects/test.txt")));
       //内容写入到文件
       printwriter.printf("姓名:%s 年龄:%d 工资:%1.2f",name,age,salary);
      printwriter.close();
    }
}

(2)格式化字符串

public static String format(String format, Object... args)

范例:格式化字符串

public class Test {
    public static void main(String[] args) throws Exception {
        String name="rachel";
        int age=18;
        double salary=8000.00;
        String str=String.format("姓名:%s 年龄:%d 工资:%1.2f",name,age,salary);
        System.out.println(str);
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值