首页 > 解决方案 > 打印到文件所有数据类型(记录器)

问题描述

我有一个类文件,其方法采用字符串参数并输出到文件:

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 很陌生,所以如果这实际上是一项微不足道的任务,我深表歉意!

标签: javalogging

解决方案


声明第二个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”。


推荐阅读