Java文件中的其他流及File类

Java文件中的其他流及File类,第1张

Java文件中的其他流及File类 Java文件中的其他流及File类

文章目录
    • Java文件中的其他流及File类
      • 一、标准输出流

一、标准输出

1.标准输出流PrintStream默认输出到控制台。
(1)合起来写

System.out.println("hello world");

(2)分开写

package exercise;
import java.io.PrintStream;

public class Seven {
    public static void main(String args[]) {
        PrintStream ps=System.out;
        ps.println("hello world");

    }
}

2.输出到指定文件
设计一个日志记录工具

package exercise;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;

public class Seven {
    public static void main(String args[]) {
        Logger logger=new Logger();
        logger.log("尝试登录,但验证失败");
        logger.log("成功登陆");
        logger.log("下线");
    }
}

class Logger{
    public static void log(String message){
        try{
            PrintStream out=new PrintStream(new FileOutputStream("log.txt",true));//输出到日志
            //改变输出方向
            System.setOut(out);
            //日期
            Date nowtime=new Date();
            //初始化时间
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
            String strTime=sdf.format(nowtime);

            System.out.println(strTime+":"+message);
            }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }

    }
}

输出结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5612046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存