Java中PrintStream流使用 以及使用PrintStream流在文件中输入时间

下面的代码我们先了解一下PrintStream流

import java.io.PrintStream;

/*标准输出流*/
/*标准字节输出流,默认输出到控制台*/
public class PrintStreamTest {
    public static void main(String[] args) {
      //联合写
        System.out.println("hello word");
      // 分开写
        PrintStream ps  = System.out;
        ps.println("hello word");
    }
}

public class PrintStreamTest {
    public static void main(String[] args) {
/*        System.out.println("hello word");
        PrintStream ps  = System.out;
        ps.println("hello word");*/

        try {
            /*字节输出流*/
            FileOutputStream fos = new FileOutputStream("E:\\IDEA\\Java\\StudentTwo\\src\\IOTest\\log.txt");
            PrintStream printStream = new PrintStream(fos);
            /*标准输出流不再指向控制台,而是指向log文件*/
            System.setOut(printStream);

            System.out.println("hello word");
            System.out.println("我是一个大帅哥");
            /*仍需要刷新*/
            printStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
/*           这个流不需要我们关闭,因为它会自己关闭*/
    }
}

运行程序之后,结果并没有在控制台显示,而是在log文件中显示

为了加深使用,我们再来写一个,将日期输出在log文件之中

代码如下所示 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PrintStreamTest02 {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("\\E:\\IDEA\\Java\\StudentTwo\\src\\IOTest\\log.txt");
            PrintStream printStream = new PrintStream(fos);
            System.setOut(printStream);

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  SSS");
            String time = sdf.format(date);
            System.out.println(time);

            printStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我爱布朗熊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值