有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将带有5个并行数组的输出表从主类打印到。txt文件?

我试图使用一个类来打印(附加)到。txt文件。到目前为止我一直不成功。我使用一个简单的logger类来输出简单的字符串,但是如何将输出输出到控制台和。txt文件

当前控制台输出:

11/18/20 14:09:24
Current status of all items being tracked:
Item|             Supply on hand| Last 24 Hr Usage|    Days on hand|          Status|
-------------------------------------------------------------------------------------

1                               1                1                1         Critical 

Process finished with exit code 0

主要课程代码:

        //Display all data, collected and calculated
        System.out.println("Current status of all items being tracked:");
        System.out.printf("%-16s %16s %16s %16s %16s", "Item|", "Supply on hand|", "Last 24 Hr Usage|", "Days on hand|", "Status|");
        System.out.println();
        System.out.println("-------------------------------------------------------------------------------------");
        System.out.println();

        for (int index = 0; index < items.length; index++)
            System.out.printf("%-16s %16d %16d %16d %16s \n", items[index], supplyOnHand[index], last24HourUsage[index], daysOnHand[index], status[index]);

Logger.log("How do I get my table to print here?");

记录器代码:

    public class Logger {
        public static void log(String message) throws IOException {
            try (PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true)) {
                out.write(message);
                out.close();

当前文件输出:

How do I get my table to print here?

共 (2) 个答案

  1. # 1 楼答案

    好吧,我找到了一份工作。这并不漂亮,但现在就足够了

    我正在使用:

     PrintStream o = new PrintStream(new FileOutputStream("DashboardLog.txt", true));
    

    然后

    System.setOut(o);
    System.setOut(console);
    

    将控制台输出和文件输出分开

  2. # 2 楼答案

      try (PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true)) {
                out.write(message);
                out.close();}
    catch(Exception e){
    }
    finally(){ 
                System.out.println(message);
    }
    

    ?