java - 打印到文件所有数据类型(记录器)
问题描述
我有一个类文件,其方法采用字符串参数并输出到文件:
public static void logger(String content) {
FileOutputStream fop = null;
File file;
//content = "This is the text content";
try {
file = new File("logs.txt");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我正在尝试使用此方法将跟踪日志记录添加到许多文件中,它不仅涉及字符串数据类型,还涉及双精度等...我不确定如何将双精度/整数包含到此方法中并输出.
我对 Java 很陌生,所以如果这实际上是一项微不足道的任务,我深表歉意!
解决方案
声明第二个Object
作为参数的方法。
public static void logger(Object content) {
logger(content.toString());
}
此方法将对象的字符串表示形式的日志记录委托给您之前的方法,无论其类型如何。
现在您可以调用logger()
字符串(例如,,logger("The answer")
以及任何其他类型(例如,logger(42)
)。
请注意,装箱(将原始类型(例如 )包装int
到对象中,例如Integer
)会自动发生。
如果您的目标是一次打印多个对象,则必须提供一种采用可变参数数组的方法。
public static void logger(Object... objects) {
String msg = Stream.of(objects).map(Object::toString).collect(Collectors.joining());
System.out.println(msg);
}
呼叫logger("The answer is ", 42)
将打印“答案是 42”。
推荐阅读
- java - 列表的字符串格式
- python - 如何使用pandas创建一个标识行数的列,直到下一次出现在另一列中的值?
- javascript - 移动布局 - 按行或列分组的表格
- pandas - 基于 3 列比较 2 个数据框并更新第二个数据
- amazon-web-services - 无法使用 boto3 停用 Amazon S3 存储桶上的对象锁定
- r - 如何编辑图例标题和标签?
- javascript - 将 API 数据分配给 Javascript 中的变量
- python - 如何在最大值条件下保持重复观察?
- javascript - 如何在charts.js中将动态字符串作为数据集传递
- python - 无法使用 Anaconda 解释器在 PyCharm GUI 中安装 OpenCV