I/O流之--打印流

4 篇文章 0 订阅
1 篇文章 0 订阅

什么是打印流
打印流是输出最方便的类
主要包含字节打印流PrintStream,字符打印流PrintWriter
方法:
void print(String str): 输出任意类型的数据,
void println(String str): 输出任意类型的数据,自动写入换行操作

PrintStream是OutputStream的子类,把一个输出流的实例传递到打印流之后,可以更加方便地输出内容,相当于打印流把输出流重新包装一下
例子1:

 /* 
 * 需求:把指定的数据,写入到printFile.txt文件中
 * 
 * 分析:
 *  1,创建流
 *  2,写数据
 *  3,关闭流
 */
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        //创建流
        //PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"));
        PrintWriter out = new PrintWriter("printFile.txt");
        //2,写数据
        for (int i=0; i<5; i++) {
            out.println("helloWorld");

        }
        //3,关闭流
        out.close();
    }
}

例子2:

public class Demo {
    public static void main(String[] args) throws IOException {
        // PrintStream流输出
        PrintStream ps1 = new PrintStream(new File("a.txt"));
        PrintStream ps2 = new PrintStream(new File("b.txt"));
        ps1.println("24");
        ps1.print("1 + 1 =" + 2);// 更加方便的输出内容
        ps2.print(24);// 此方法被重载很多次
        ps1.close();
        ps2.close();

        // PrintStream流printf方法格式化输出
        String name = "王五";
        int age = 20;
        float high = 1.68f;
        char sex = '男';
        PrintStream ps3 = new PrintStream(new FileOutputStream(
                new File("c.txt")));
        ps3.printf("姓名: %s; 年龄: %d; 身高 %f; 性别: %c", name, age, high, sex);
    }
}

顺便提一下System类
System类对打印流的支持

System类的三个常量:

public static final PrintStream out

public static final PrintStream err

public static final InputStream in

system.out是PrintStream的对象

打印流是最简单的,小伙伴们看懂了没!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值