简体   繁体   English

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

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

The Java application that I support is logging some details in a flat file. 我支持的Java应用程序是在平面文件中记录一些细节。 the problem I face some times is that, the entry is very low compared to the previous day. 我有些时候面临的问题是,与前一天相比,这个条目非常低。 This entry is most essential because our reports are generated based on the file. 此条目是最重要的,因为我们的报告是基于该文件生成的。 I went thro code for writing I couldn't figure out any issues. 我去写代码我无法弄清楚任何问题。 the method which is writing is sync method. 写入的方法是同步方法。

Any suggestions? 有什么建议么? I can also provide the code for you is you may need? 我也可以为您提供您可能需要的代码吗?

 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 ();
    }
}

You've created a FileOutputStream , but aren't closing that stream. 您已创建了FileOutputStream ,但未关闭该流。 Close that stream and try again. 关闭该流并再试一次。 That might be causing the problem. 这可能会导致问题。

Messages are getting logged sometime because the garbage collector kicks in at some intervals and closes the FileOutStream . 消息会在某个时间被记录,因为垃圾收集器会以某些间隔启动并关闭FileOutStream This then allows messages to be logged again. 然后,这允许再次记录消息。 You're getting the unreachable error since you have a return statement in both the if & else blocks. 您收到了无法访问的错误,因为在ifelse块中都有return语句。 You'll have to take the PrintWriter and FileOutStreamWriter out of the getPrintWriter put it where you usually call the getPrintWriter() . 你必须采取PrintWriterFileOutStreamWriter出的getPrintWriter把它放在你通常所说的getPrintWriter() Then you'll be able to close the streams correctly. 然后,您将能够正确关闭流。 getPrintWriter should only ensure file exists, so rename it to ensureFileExistance getPrintWriter应该只保证文件存在,所以将它重命名为ensureFileExistance

If you can use Apache Common IO, try this: 如果您可以使用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 ();
    }
}

In Common IO 2.1, you can append a file that you are writting to. 在Common IO 2.1中,您可以追加要写入的文件。 You can now get rid of the closePW and getPrintwriter and since the log method is synchronized , the file can be written one at a time from the same object. 您现在可以删除closePWgetPrintwriter并且由于日志方法已synchronized ,因此可以从同一对象一次写入一个文件。 However, if you try to write the same file from different object at the same time, you will end up having overwritting problem. 但是,如果您尝试同时从不同对象写入同一文件,最终会出现覆盖问题。

Also, Common IO create the missing parent folder for you automatically. 此外,Common IO会自动为您创建缺少的父文件夹。 There is no need to explicitly check and create the folder. 无需显式检查和创建文件夹。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM