Java写入文本文件无法正常工作

时间:2011-12-13 02:29:43

标签: java

我支持的Java应用程序是在平面文件中记录一些细节。我有些时候面临的问题是,与前一天相比,这个条目非常低。此条目是最重要的,因为我们的报告是基于该文件生成的。我去写代码我无法弄清楚任何问题。写入的方法是同步方法。

有什么建议吗?我也可以为您提供您可能需要的代码吗?

 public synchronized void log (String connID, String hotline, String callerType,
        String cli, String lastMenu, String lastInput,
        String status, String reason)
   {
    //String absoluteFP = LOG_LOC + ls + this.getFilename();

    //PrintWriter pw = this.getPrintWriter(absoluteFP, true, true);

    try
    {
        pw.print (this.getDateTime ()+ ","+connID +","+hotline+","+callerType+","+ cli+"," +   lastMenu + "," + lastInput + "," + status + "," + reason);               


        //end 1006
        pw.print (ls);
        pw.flush ();
        //pw.close();
    }
    catch (Exception e)
    {
        e.printStackTrace ();
        return;
    }
}

private synchronized PrintWriter getPrintWriter (String absoluteFileName,
        boolean append, boolean autoFlush)
{
    try
    {
        //set absolute filepath
        File folder = new File (absoluteFileName).getParentFile ();//2009-01-23

        File f = new File (absoluteFileName);

        if (!folder.exists ())//2009-01-23
        {
            //System.out.println ("Call Detailed Record folder NOT FOUND! Creating a new);     
            folder.mkdirs ();

            //System.out.println ("Configure log folder");
            this.setHiddenFile (LOG_LOC);//set tmp directory to hidden folder

            if (!f.exists ())
            {
                //System.out.println ("Creating a new Call Detailed Record...");//2009-01-23

                f.createNewFile ();//2009-01-23

                               }
        }
        else
        {
            if (!f.exists ())
            {
                //System.out.println ("Creating a new Call Detailed Record...");//2009-01-23

                f.createNewFile ();//2009-01-23


            }
        }

        FileOutputStream tempFOS = new FileOutputStream (absoluteFileName, append);
        if (tempFOS != null)
        {
            return new PrintWriter (tempFOS, autoFlush);
        }
        else
        {
            return null;
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace ();
        return null;
    }
}

          /**
             * Set the given absolute file path as a hidden file.
        * @param absoluteFile String
      */
     private void setHiddenFile (String absoluteFile)
       {
    //set hidden file
    //2009-01-22, KC
    Runtime rt = Runtime.getRuntime ();
    absoluteFile = absoluteFile.substring (0, absoluteFile.length () - 1);//2009-01-23
    try
    {
      System.out.println (rt.exec ("attrib +H " + "\"" + absoluteFile +        "\"").getInputStream ().toString ());
    }
    catch (IOException e)
    {
        e.printStackTrace ();
    }
}

private String getDateTime ()
{
    //2011-076-09, KC-format up to milliseconds to prevent duplicate PK in CDR table.
    //return DateUtils.now ("yyyy/MM/dd HH:mm:ss");
    return DateUtils.now ("yyyy/MM/dd HH:mm:ss:SSS");
    //end 0609
}

private String getFilename ()
{
    ///return "CDR_" + port + ".dat";//2010-10-01
    return port + ".dat";//2010-10-01
}

public void closePW ()
{
    if (pw != null)
    {
        pw.close ();
    }
}

2 个答案:

答案 0 :(得分:1)

您已创建FileOutputStream,但未关闭该流。关闭该流并再试一次。这可能会导致问题。

有时会记录消息,因为垃圾收集器会在某个时间间隔内启动并关闭FileOutStream。然后,这允许再次记录消息。由于您在returnif中都有else声明,因此您收到了无法访问的错误PrintWriter阻止。您必须从FileOutStreamWriter中取出getPrintWritergetPrintWriter(),将其放在通常称为getPrintWriter的位置。然后,您将能够正确关闭流。 ensureFileExistance应该只确保文件存在,因此将其重命名为{{1}}

答案 1 :(得分:1)

如果您可以使用Apache Common IO,请尝试:

public synchronized void log(String connID, String hotline, String callerType,
        String cli, String lastMenu, String lastInput,
        String status, String reason) {
    String absoluteFP = LOG_LOC + ls + this.getFilename();
    File file = new File(absoluteFP);
    String message = this.getDateTime() + "," + connID + "," + hotline + "," + callerType + "," + cli + "," + lastMenu + "," + lastInput + "," + status + "," + reason;
    try {
        // note that you must explicitly add new line character if you want the line to end with newline
        FileUtils.write(file, message + "\n", "UTF-8", true);
    } catch (IOException ex) {
        ex.printStackTrace ();
    }
}

在Common IO 2.1中,您可以附加要写入的文件。您现在可以删除closePWgetPrintwriter,并且由于日志方法是synchronized,因此可以从同一对象一次写入一个文件。但是,如果您尝试同时从不同对象写入同一文件,最终会出现覆盖问题。

此外,Common IO会自动为您创建缺少的父文件夹。无需显式检查和创建文件夹。