【IntelliJ IDEA 2019.2】java 自写的log打印及读写文件
发布日期:2021-05-13 00:03:34 浏览次数:14 分类:精选文章

本文共 1280 字,大约阅读时间需要 4 分钟。

清空日志

在日志文件中清空内容可以通过将字符串写入文件实现。具体操作如下:

static public void ClearDstFile() {
try {
FileOutputStream fos = new FileOutputStream("log_command.txt", false); // 设置追加模式为false
String str = ""; // 存储要写入的内容
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

追加日志

将具体内容追加到现有日志文件中,可以使用Formatter进行格式化输出。具体实现如下:

static public void AppendStringToFile(String format, Object... args) {
try {
String str = new Formatter().format(format, args).toString();
System.out.print(str); // 输出控制台
FileOutputStream fos = new FileOutputStream("log_command.txt", true); // 设置追加模式为true
fos.write(str.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

附件一:Java 读写文件

读取文件

try {
// 创建读取文件的字节流
FileInputStream fis = new FileInputStream(path);
System.out.printf("Input file <<%s>> size is %dk\n", path, fis.available()/1024);
byte[] FileBuf = new byte[fis.available()];
fis.read(FileBuf);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}

写入文件

try {
FileOutputStream fos = new FileOutputStream(OutputBinName);
fos.write(RGB16tab);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
上一篇:【IntelliJ IDEA 2019.2】批处理运行 java class 文件
下一篇:【IntelliJ IDEA 2019.2】java log4j 最简用法及进阶用法

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2025年04月29日 06时14分13秒