在文本文件中输出变量

时间:2014-09-25 15:19:05

标签: java eclipse ubuntu-12.04

我有一些像这里的Java代码:

public synchronized void printLinkStatistics(Logger log)
{
    log.info("\tInput Port = " + inputPort);
    Set <Long> ts = statData.keySet();
    for(Long t: ts)
    {   double utilization = statData.get(t);
        if (utilization!=0.0) 
        {
            utilization *= 8.0;
            utilization /= 1e6;
            if (!Double.isNaN(utilization))
            {
            log.info("\t\tTimestamp = " + t + ", Utilization = " + utilization + "Mbps");

           }
        }
    }
}

并且此代码将在控制台中编写利用率,但我还需要在文件中写入利用率+时间戳以在将来绘制试用版。 我如何用这个变量创建文件? 我在Ubuntu 12.04中使用Eclipse

EDITH 我这样做但文件是空的:

public synchronized void printLinkStatistics(Logger log)
{ 
    try
    {
    PrintWriter pw = new PrintWriter(new File("output.txt"));
    log.info("\tInput Port = " + inputPort);
    Set <Long> ts = statData.keySet();
    for(Long t: ts)
    {   double utilization = statData.get(t);
        if (utilization!=0.0) 
        {
            utilization *= 8.0;
            utilization /= 1e6;
            if (!Double.isNaN(utilization))
            {
            log.info("\t\tTimestamp = " + t + ", Utilization = " + utilization + "Mbps");
            pw.println("\t\tTimestamp = " + t + ", Utilization = " + utilization + "Mbps");
            }
        }
    }
    }
    catch (FileNotFoundException e) {
        e.printStackTrace(); //handle exception as you want
                                        }
}

1 个答案:

答案 0 :(得分:1)

您可以使用PrintWriter并将输出重定向到文件。 PrintWriter有许多有用的方法,可以使编写输出更容易(阅读java文档了解更多信息)。 E.g。

PrintWriter pw = new PrintWriter(new File("output.txt"));
pw.println("hello");
pw.flush();

您的更新代码将如下所示

public synchronized void printLinkStatistics(Logger log, PrintWriter writer)
{
    log.info("\tInput Port = " + inputPort);
    Set <Long> ts = statData.keySet();
    for(Long t: ts)
    {   double utilization = statData.get(t);
        if (utilization!=0.0) 
        {
            utilization *= 8.0;
            utilization /= 1e6;
            if (!Double.isNaN(utilization))
            {
            log.info("\t\tTimestamp = " + t + ", Utilization = " + utilization + "Mbps");
      writer.println("\t\tTimestamp = " + t + ", Utilization = " + utilization + "Mbps");

           }
        }
    }
    writer.flush();
}

为了调用您的方法,您需要将代码包装在try/catch块中,如此

try {
    PrintWriter pw = new PrintWriter(new File("output.txt"));
    printLinkStatistics(logger, pw);
} catch (FileNotFoundException e) {
    e.printStackTrace(); //handle exception as you want
}