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);
    }
}
发布了50 篇原创文章 · 获赞 39 · 访问量 8292

猜你喜欢

转载自blog.csdn.net/Racheil/article/details/89299279