Java IO流--打印流PrintStream和PrintWriter的使用详解

博主前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住也分享一下给大家,
👉点击跳转到网站

打印流:
PrintStream 和 PrintWriter
提供了一系列重载的print()和println()

PrintStream的具体使用,代码如下:

public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream printStream = System.out;
        //在默认情况下,PrintStream输出数据的位置是标准输出,即显示器
        /*
        public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
        }
         */
        printStream.println("hello,world");
        //因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
        printStream.write("hello,筱路".getBytes());
        printStream.close();

        //我们可以去修改打印流输出的位置/设备
        //1.输出修改成到"D:\\f1.txt"
        //2."hello,筱路" 就会输出到"D:\\f1.txt"
        //3.public static void setOut(PrintStream out) {
        //        checkIO();
        //        setOut0(out); //native 方法 底层调用c/c++ 修改了out
        //    }
        System.setOut(new PrintStream("D:\\f1.txt"));
        System.out.println("hello,筱路!");
    }
}

PrintWriter的具体使用,代码如下:

public class PrintWriter_ {
    public static void main(String[] args) throws IOException {
//        PrintWriter printWriter = new PrintWriter(System.out);
        PrintWriter printWriter = new PrintWriter(new FileWriter("D:\\f3.txt"));
        printWriter.print("北京你好~!");
        printWriter.close();//flush+关闭流,才会将数据写入到文件
    }
}
@Test
    public void test1(){
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\Temp\\text.txt"));
            //创建打印输出流,设置为自动刷新模式(写入换行符或字节'\n'时都会刷新输出)
            ps = new PrintStream(fos, true);
            if (ps != null) {//把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }
            for (int i = 0; i <= 255; i++) {
                System.out.print((char) i);
                if (i % 50 == 0) { //每50个数据一行
                    System.out.println(); //换行
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ps!=null) {
                ps.close();
            }
        }
    }

在硬盘中显示文件内容:

 
	

 !"#$%&'()*+,-./012
3456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd
efghijklmnopqrstuvwxyz{|}~€‚ƒ„
†‡ˆ‰Š‹ŒŽ‘’“”•–
—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈ
ÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùú
ûüýþÿ
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路宇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值