BufferedWriter输出流的使用

本文介绍了一种使用Java进行日志记录的方法,包括利用BufferedWriter进行BI/O操作来追加日志,以及使用NIO进行文件写入。探讨了如何格式化日期时间并将其与日志消息一起写入文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.lzxa.analyze.common;


import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 输入流(用于排查错误和测试日志使用)
 */
public class IOBufferedWriter {

   static public void BIOBufferedWriters(String name)  {
        try{
            //1.创建BufferedWriter类型的对象与c:/a.txt文件关联
            //true代表可以追加,
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("c:/a.txt",true)));
            
            //时间转字符串格式化(DateTimeFormatter是线程安全的)
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            //输出当前时间
            LocalDateTime dateTime01 = LocalDateTime.now();
            String format = dateTime01.format(formatter);

            //2.将字符串数据"last demo!"写入文件中
            bw.write(format+":"+name+ "\r\n");
            //3.关闭流对象并释放有关的资源
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }


    static public void NIOBufferedWriters() throws Exception {
        String str ="hello world";
  //先构建输入流,true是追加内容
            FileOutputStream fileOutputStream = new FileOutputStream("/Users/1.txt",true);
        //通过流获取通道
        FileChannel channel = fileOutputStream.getChannel();
        //创建缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将数据放入缓冲区
        buffer.put(str.getBytes());
        try {
            //需要清空缓冲区的标记,再进行操作
            buffer.flip();
            //将内容写到通道中
            channel.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //关闭
        fileOutputStream.close();
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员s

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

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

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

打赏作者

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

抵扣说明:

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

余额充值