java - 是否有另一个库可以允许写入文档(例如日志)“日期”类型,因为 FileOutputStream 不允许它?
问题描述
我有以下代码,并希望将日期、计数和 true(日期、int 和布尔类型)等信息写入我的文件(例如 atm.log)。此外,当我删除 Date 和 boolean 类型时,编译通过,但文件最终没有计数。我不确定为什么当日期和布尔值被忽略时它不包括计数,因为我有'close()'方法。
主要的:
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
File myObj = new File("atm.log");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//while(true)
//{
ATM atm = new ATM();
atm.init();
atm.run();
//}
}
}
班级:
import java.util.Date;
import java.util.ArrayList;
public class UserInfo
{
private final Date date;
private final int count;
private final boolean correct;
public UserInfo(Date date, int count, boolean correct)
{
this.date = date;
this.count = count;
this.correct = correct;
}
public Date getDate()
{
return date;
}
public int getCount()
{
return count;
}
public boolean isCorrect()
{
return correct;
}
}
班级:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.*;
import java.io.FileOutputStream;
public class Logger
{
ArrayList<UserInfo> obj = new ArrayList<>();
public Logger(Date date, int count, boolean correct){
//obj.get(0).setValue(date,count, correct);
obj.add(new UserInfo(date, count, correct));
try (FileOutputStream out = new FileOutputStream("atm.log")) {
for (UserInfo s : obj)//int i = 0; i < obj.size(); i++
{
out.write(s.getCount());
out.write(s.getDate());
out.write(s.isCorrect());
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
错误:
java: no suitable method found for write(java.util.Date)
method java.io.FileOutputStream.write(int) is not applicable
(argument mismatch; java.util.Date cannot be converted to int)
method java.io.FileOutputStream.write(byte[]) is not applicable
(argument mismatch; java.util.Date cannot be converted to byte[])
解决方案
通常,写入文件与格式无关,也就是说,这取决于您。可以使用 JSON、XML、CSV 等来应用常见格式,但所有这些决定都会增加不同程度的复杂性。
因此,例如,一个简单的解决方案可能是定义一种人类可读的格式,例如......
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
Logger logger = new Logger();
logger.log(LocalDateTime.now(), 100, true);
logger.log(LocalDateTime.now(), 200, false);
logger.log(LocalDateTime.now(), 300, true);
logger.log(LocalDateTime.now(), 400, false);
logger.log(LocalDateTime.now(), 500, true);
logger.dump();
}
public class Logger {
private ArrayList<UserInfo> obj = new ArrayList<>();
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd-HH:mm:ss");
public Logger() {
}
public void log(LocalDateTime date, int count, boolean correct) {
UserInfo info = new UserInfo(date, count, correct);
obj.add(info);
// You could keep the file open until the class in closed
try (BufferedWriter bw = new BufferedWriter(new FileWriter("atm.log", true))) {
String text = String.format("[%s] %4d %s", formatter.format(info.getDate()), info.getCount(), info.isCorrect() ? "Yes" : "No");
bw.write(text);
bw.newLine();;
} catch (IOException e) {
e.printStackTrace();
}
}
public void dump() {
try (BufferedReader br = new BufferedReader(new FileReader("atm.log"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class UserInfo {
private final LocalDateTime date;
private final int count;
private final boolean correct;
public UserInfo(LocalDateTime date, int count, boolean correct) {
this.date = date;
this.count = count;
this.correct = correct;
}
public LocalDateTime getDate() {
return date;
}
public int getCount() {
return count;
}
public boolean isCorrect() {
return correct;
}
}
}
这将打印类似...
[2021/10/08-08:46:15] 100 Yes
[2021/10/08-08:46:15] 200 No
[2021/10/08-08:46:15] 300 Yes
[2021/10/08-08:46:15] 400 No
[2021/10/08-08:46:15] 500 Yes
一些笔记...
我已经LocalDateTime
优先使用Date
,这是我们现在应该做的事情,但基本概念将与Date
and一起使用SimpleDateFormatter
。
我需要创建一个新的实例Logger
来添加一个新的日志条目,然后将其添加到List
... 并且每个Logger
实例都覆盖了以前的文件,这是没有意义的。
所以,相反,我创建Logger
了支持多个日志输出并每次都附加到文件中。
推荐阅读
- matplotlib-basemap - cartopy中底图的npts功能的替代功能是什么?
- java - 如何在实体类中查找没有属性
- python - AttributeError:“list”对象没有属性“h3”(Beautifulsoup)
- google-chrome-extension - Chrome 扩展更改边框半径和位置
- c# - 为什么 HttpClient 似乎在没有 .Result 的情况下挂起?
- mysql - 我如何分组,排序和取出mysql中的第一个N?
- c++ - 是否有一个库/代码被剪断,它可以将网格转换为向量表示中的 sdf 以实现亚体素精确表示?
- css - 如何在 Shiny 中将图标添加到 downloadButton?
- sql - 根据 PostgreSQL 中的条件选择组内的一行
- angular - 如果我使用 Bootstrap 链接,我的 Bootstrap 导航栏会像表格一样形成