簡體   English   中英

Java寫入文本文件無法正常工作

[英]Java writing to a text file not working properly

我支持的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 ();
    }
}

您已創建了FileOutputStream ,但未關閉該流。 關閉該流並再試一次。 這可能會導致問題。

消息會在某個時間被記錄,因為垃圾收集器會以某些間隔啟動並關閉FileOutStream 然后,這允許再次記錄消息。 您收到了無法訪問的錯誤,因為在ifelse塊中都有return語句。 你必須采取PrintWriterFileOutStreamWriter出的getPrintWriter把它放在你通常所說的getPrintWriter() 然后,您將能夠正確關閉流。 getPrintWriter應該只保證文件存在,所以將它重命名為ensureFileExistance

如果您可以使用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會自動為您創建缺少的父文件夾。 無需顯式檢查和創建文件夾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM