美文网首页
2019-03-26

2019-03-26

作者: 昕柒 | 来源:发表于2019-03-26 15:32 被阅读0次

java——打印流:

打印流主要是用来输出信息的,主要分为字节打印流(PrintStream)和字符打印流(PrintWriter)

  • PrintStream:就是OutStream的子类;
  • PrintWriter:就是Writer的子类;

PrintStream:

package Demo0322;

import java.io.*;

public class PrintStreamDemo01 {
    public static void main(String[] args) {
        //实例化file
        File file = new File("e:"+File.separator+"a"+File.separator+"ceshi.xml");
        //先使用outputstream处理文件有可能找不到的异常
        OutputStream out = null;
        try {
            out = new FileOutputStream(file,true);
        }catch(Exception e) {
            e.printStackTrace();
        }
        //实例化PrintStream(out说明一定有文件了,就不用加异常了),要想使用print就不用向上转型
        PrintStream ps = new PrintStream(out);
        try {
            //将字节数组一次性写入文件,使用outStream中继承的方法
            ps.write("记得转成字节写入".getBytes());//将字符串转成字节写入
            ps.write("\r\n".getBytes());//换行
            ps.write("记得转成字节写入".getBytes(),0,3);//将字符串转成字节写入前两个字
            //使用printStream自己的方法
            ps.print(10);
            ps.print("a b c d");
            ps.println("我来写入汉字");
            ps.printf("姓名=%s, 年龄=%d,成绩=%f","张三",18,93.4);
            ps.close();//关闭
        }catch(Exception e) {
            e.printStackTrace();
        }
        
        
    }
}

在这里插入图片描述

printWriter:
err也是输出,只不过字是红色的,有提示的意思

package Demo0322;

public class PrintWriteDmeo01 {
    public static void main(String[] args) {
        System.err.println("错误的提示");
        
        //System.out是PrintStream,所以才可以调用PrintStream中的方法
        System.out.println("Hello World");
        System.out.print(123.321);
        try {
            System.out.write("将字转成字节".getBytes());
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.printf("姓名=%s,性别=%s,年龄=%d,英语成绩=%f","李四","男",18,85.4);

输出的内容:


在这里插入图片描述

相关文章

网友评论

      本文标题:2019-03-26

      本文链接:https://www.haomeiwen.com/subject/dbngvqtx.html