Java 打印到所有数据类型的文件(记录器)
我有一个类文件,其中包含一个方法,该方法接受一个字符串参数并输出到一个文件:Java 打印到所有数据类型的文件(记录器),java,logging,Java,Logging,我有一个类文件,其中包含一个方法,该方法接受一个字符串参数并输出到一个文件: 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 FileOu
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();
}
}
}
我正在尝试使用此方法向许多文件添加跟踪日志记录,它不仅涉及字符串数据类型,还涉及双倍等。。。我不知道如何将double/int包含到这个方法和输出中
我对Java非常陌生,如果这是一项非常琐碎的任务,我深表歉意 声明第二个将
对象
作为参数的方法
public static void logger(Object content) {
logger(content.toString());
}
此方法将对象的字符串表示形式的日志记录委托给以前的方法,而不管其类型如何
现在,您可以对字符串调用logger()
(例如,logger(“答案”)
,以及任何其他类型(例如,logger(42)
)
请注意,装箱(将基本类型(如int
)包装到对象(如Integer
)中)是自动进行的
如果您的目标是一次打印多个对象,则必须提供一个采用varargs数组的方法
public static void logger(Object... objects) {
String msg = Stream.of(objects).map(Object::toString).collect(Collectors.joining());
System.out.println(msg);
}
调用
记录器(“答案是”,42)
将打印“答案是42”。您可以使用相应的包装器类获得双精度、长精度等的字符串表示形式
例如:
double doubVar = 12.643;
Logger.logger( Double.toString( doubVar ) );
或对于整数:
int i = 2;
Logger.logger( Integer.toString( i ) );
谢谢你的帮助…但是如果我想要例如:Logger.Logger(“Value is:”,Double.valueOf(doubVar).toString());@arsenal88从这一点上讲,它是一个简单的字符串连接。toString()
method返回字符串,您可以随意使用它执行任何操作。因此,您可以执行类似以下操作:Logger.Logger(“值为:”+Double.valueOf(val.toString())
。请注意用于连接字符串的+
运算符。顺便说一句,大多数代码都不需要,关闭每个日志上的文件非常昂贵。如果您是Java新手,我建议您使用一个标准记录器。Java中至少有5个流行的记录器,包括一个bult。