Problem with Copying and Renaming File once it reaches a limit

Discussion in 'Java' started by Buddha, Aug 8, 2007.

  1. Buddha

    Buddha Guest

    Dear all,

    Following is the code I wrote. I have a simple requirement. I need to
    update a log file (txt file) everyday. For which, I initally take a
    file.. and append it with some text. once it reaches a certain size. I
    rename that file and append it with todays date. However, since the
    file may reach the specified size at any given point. I take the
    length of the file and append to the file name.. and decrement the
    length. As of now, It is making only Two files. One the main file..
    and second the renamed file.
    The problem is for some reason the length gets stuck at 49. Then I
    realise it is because the first file is being checked every time(I
    check for the size).
    Could some body please tell me how I could correct this code :


    code:
    --------------------------------------------------------------------------------

    import java.io.BufferedWriter;import java.io.FileWriter;import
    java.io.IOException;import java.text.*;import
    java.util.Calendar;import java.util.Date; public class File1 { public
    static void main(String[] args) { String nameRename; java.io.File
    file; // Date d = new Date(); Calendar c = Calendar.getInstance();
    String date1= new String(); //nameRename += d.getMonth); try
    { Date today = Calendar.getInstance().getTime();
    DateFormat shortFormatter =
    SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT ); //
    create a long version date formatter DateFormat longFormatter =
    SimpleDateFormat.getDateInstance( SimpleDateFormat.LONG ); date1 =
    (String)longFormatter.format( today ); System.out.println("DATE 1 is
    "+date1); file = new java.io.File("C://dblog"); // Create file if
    it does not exist boolean exist = file.createNewFile(); if (!exist)
    { System.out.println("File already exists."); }else{
    System.out.println("File created successfully."); } long length =
    file.length(); if(length == 1 || length > 1){ int i = 0;
    i=(int)length; // File (or directory) with new name
    System.out.println("entering here"); file = new java.io.File(file
    +date1+i); // Rename file (or directory) boolean success
    = file.renameTo(file); if (success) {
    System.out.println("Successfully renamed !");
    file.createNewFile(); // File was not successfully
    renamed } else{ System.out.println("renaming
    failed"); } i--; } System.out.println("lenght is
    "+length); BufferedWriter out = new BufferedWriter(new
    FileWriter(file, true)); out.newLine(); /* uncomment this for non-
    windows files*/ //out.write("\r"); out.write("testing for database
    update transaciton logging"); out.close(); }catch (IOException e)
    { } catch(Exception e1){ } }

    *********
    P.S :
    Yes I think, I have areason I cant use log4j for this.
    Because AFAIK log4j doesnt give me any other logging level other than
    the defaults ( debug,info,...,fatal ......for which am using log4j to
    only log the warnings and fatals).
    Where as this code, I will modify and have a static method being
    called in my DAOs with params to append to this file.

    I specifically need to be able to add the logs for updates or deletes,
    so I have to write statements in my DAOs.Is there a simple way I can
    include *this* functionality using Log4j, curently am using it for
    logging application related stuff. I have done a lot of googling for
    this.. but they are way too complex for me to follow. I am crushed
    under deadlines . If you know of a better way or a solution to
    this... I will be grateful.

    Rgds
     
    Buddha, Aug 8, 2007
    #1
    1. Advertising

  2. Buddha

    Roedy Green Guest

    code that messy is downright insulting. It a ****-you slap in the face
    to your readers.

    Here it is untangled:

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.*;
    import java.util.Calendar;
    import java.util.Date;
    public class File1
    {
    public static void main(String[] args)
    {
    String nameRename;
    java.io.File file;
    // Date d = new Date();
    Calendar c = Calendar.getInstance();
    String date1= new String();
    //nameRename += d.getMonth);
    try
    {
    Date today = Calendar.getInstance().getTime();
    DateFormat shortFormatter =
    SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT );
    // create a long version date formatter
    DateFormat longFormatter = SimpleDateFormat.getDateInstance(
    SimpleDateFormat.LONG );
    date1 = (String)longFormatter.format( today );

    System.out.println("DATE 1 is"+date1);
    file = new java.io.File("C://dblog");
    // Create file if it does not exist
    boolean exist = file.createNewFile();
    if ( !exist )
    {
    System.out.println("File already exists.");
    }
    else
    {
    System.out.println("File created successfully.");
    }
    long length = file.length();
    if ( length == 1 || length > 1 )
    {
    int i = 0;
    i=(int)length;
    // File (or directory) with new name

    System.out.println("entering here");
    file = new java.io.File(file +date1+i);

    // Rename file (or directory) boolean success
    = file.renameTo(file);
    if ( success )
    {
    System.out.println("Successfully renamed !");
    file.createNewFile();
    // File was not successfully renamed
    }
    else
    {
    System.out.println("renaming failed");
    }
    i--;
    }
    System.out.println("length is "+length);
    BufferedWriter out = new BufferedWriter(new FileWriter(file,
    true));
    out.newLine();
    /* uncomment this for non-windows files*/
    //out.write("\r");
    out.write("testing for database update transaction logging");
    out.close();
    }
    catch ( IOException e )
    {
    }
    catch ( Exception e1 )
    {
    }
    }

    --
    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Aug 8, 2007
    #2
    1. Advertising

  3. Buddha

    Buddha Guest

    On Aug 8, 11:21 am, Roedy Green <>
    wrote:
    > code that messy is downright insulting. It a ****-you slap in the face
    > to your readers.


    Uh oh... I am sorry about that. I am posting code here for the first
    time. I took it out of an editor and put it here directly. will make
    sure it is indented properly from the next time.

    Rgds
     
    Buddha, Aug 8, 2007
    #3
  4. Buddha

    Lew Guest

    Buddha wrote:
    > P.S :
    > Yes I think, I have areason I cant use log4j for this.
    > Because AFAIK log4j doesnt give me any other logging level other than
    > the defaults ( debug,info,...,fatal ......for which am using log4j to
    > only log the warnings and fatals).


    What other logging level(s) do you need?

    > Where as this code, I will modify and have a static method being
    > called in my DAOs with params to append to this file.


    How does that affect the choice to use log4j or not?

    > I specifically need to be able to add the logs for updates or deletes,
    > so I have to write statements in my DAOs.Is there a simple way I can
    > include *this* functionality using Log4j, curently am using it for
    > logging application related stuff.


    It's no different from any other use of logging statements. You insert calls
    to log.debug() or whatever level at whatever point in whatever method needs
    things logged. Nothing you describe is difficult to do with log4j. I
    completely do not understand the nature of your difficulty. Can you be more
    specific about what you're trying to do with log4j, preferably with a code
    snippet that illustrates why you can't?

    --
    Lew
     
    Lew, Aug 8, 2007
    #4
  5. Buddha

    Buddha Guest

    I
    > completely do not understand the nature of your difficulty. Can you be more
    > specific about what you're trying to do with log4j, preferably with a code


    I am trying to log with log4j, and it is working like a charm. I have
    another requirement in my application which wants me to log changes
    made to the database. (Like: Table X updated with values ABC). For
    which, I think I cant use Log4j. Hence I came up with my custom File
    IO.

    Rgds
     
    Buddha, Aug 8, 2007
    #5
  6. Buddha

    Lew Guest

    Buddha wrote:
    > I have
    > another requirement in my application which wants me to log changes
    > made to the database. (Like: Table X updated with values ABC). For
    > which, I think I cant [sic] use Log4j. Hence I came up with my custom File
    > IO.


    This is what I don't understand, and your failure to answer my questions
    continues to deepen the mystery.

    Let's try these questions and hope for some useful feedback:

    How is it that you are not able to use log4j to log your database changes?
    Please be specific about what does not work, as in what you are trying to
    accomplish and what happens instead.

    What is different about your custom component that makes it succeed where
    log4j fails?

    Remember in my last response I asked:
    > Can you be more specific about what you're trying to do with log4j, preferably with a code snippet that illustrates why you can't?


    --
    Lew
     
    Lew, Aug 8, 2007
    #6
  7. Buddha

    Buddha Guest

    > This is what I don't understand, and your failure to answer my questions
    > continues to deepen the mystery.

    Oops..

    > Let's try these questions and hope for some useful feedback:>
    > How is it that you are not able to use log4j to log your database changes?
    > Please be specific about what does not work, as in what you are trying to
    > accomplish and what happens instead.

    I havent even tried using log4j for logging database changes ( because
    they need to go into a different log file altogether, away from
    application logs).

    > What is different about your custom component that makes it succeed where
    > log4j fails?

    Nothing. Just that My understanding of log4j is probably not
    exceptional.

    > > Can you be more specific about what you're trying to do with log4j, preferably with a code snippet that illustrates why you can't?


    This is my log4j.properties file
    *****
    # Log4j configuration file.
    log4j.rootCategory=DEBUG, A1, A2
    # Available levels are DEBUG, INFO, WARN, ERROR, FATAL
    # # A1 is a ConsoleAppender
    #
    log4j.appender.A1=org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout=org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern=%C %n %-5p [%t] - %m%n
    #
    # A2 is a DailyRollingFileAppender
    log4j.appender.A2=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.A2.file=C:/logs/logfile.log
    log4j.appender.A2.datePattern='.'yyyy-MM-dd
    log4j.appender.A2.append=true
    log4j.appender.A2.layout=org.apache.log4j.PatternLayout
    log4j.appender.A2.layout.ConversionPattern=%C %-5p %d{ISO8601} [%t] -
    %m%n
    ************************

    This is the way I use the logging
    *******
    private static final Category log =
    Category.getInstance(test.class.getName());
    PropertyConfigurator.configure("log4j.properties");
    log.warn("dis is a warning");
    log.info("Dis is a INFO");
    log.debug("Log4j really works!");
    //what level can I use to log db updates? Ex:
    log.dbchange( "Table X updated with
    // values ABC");
    //Hence here is where I can call my file updater, to
    update the changes in a log
    // file.

    ********
    This is the output in the log file
    *****
    test WARN 2007-08-09 13:06:04,828 [main] - dis is a warning
    test INFO 2007-08-09 13:06:04,890 [main] - Dis is a INFO
    test DEBUG 2007-08-09 13:06:04,890 [main] - Log4j really works!
    *****

    All I know about log4j is, I can set it up to redirect fatals,
    warnings and debugs into a log file.
    jsut to be clear, I need to log the warnings, errors and fatal
    messages in a seperate file.. and database updates in a seperate file.


    Regards
     
    Buddha, Aug 9, 2007
    #7
  8. Buddha

    Buddha Guest

    @Lew: I will still wait to hear your thoughts. I untangled this code.
    Here it is for anyone who wants to use it :
    ***********************
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.*;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.regex.*;

    public class DbLog{
    /**
    This class will append all the dblogs in a file upto the specified
    size.
    After which the contents will be copied into another file, which
    will be name
    along with a time stamp. The hencforth updations will continue in
    the file name
    specified in the properties file
    */

    static void DbLogAppend(String appendValue){
    System.out.println("Entering the static method in file1");
    WriteToFile(appendValue);
    }

    static void WriteToFile(String appendValue){
    try{
    java.util.Properties props = new java.util.Properties();
    java.net.URL url = ClassLoader.getSystemResource("props.properties");
    props.load(url.openStream());
    String fileName = (String)props.get("filename");
    String fileMaxSize = (String)props.get("fileMaxSize");
    Long longFileMaxSize =new Long(Long.parseLong(fileMaxSize));
    long longFileMaxSizept = (long)longFileMaxSize;
    String nameRename;
    java.io.File file;
    java.io.File file2;
    Calendar c = Calendar.getInstance();
    String date1= new String();
    Pattern p = Pattern.compile(":");
    String s = new String();
    Date now = new Date();
    long length;
    BufferedWriter out = null;

    try {
    file = new java.io.File(fileName);
    // Create file if it does not exist
    boolean exist = file.createNewFile();
    if (!exist){
    System.out.println("File already exists.");
    }else{
    System.out.println("File created successfully.");
    }
    length = file.length();
    if(length == longFileMaxSizept || length > longFileMaxSizept){
    System.out.println("lenght is "+length);
    s = DateFormat.getDateTimeInstance().format(now);
    // Create a matcher with an input string
    Matcher m = p.matcher(s);
    StringBuffer sb = new StringBuffer();
    boolean result = m.find();
    // Loop through and create a new String with the replacements
    while(result) {
    m.appendReplacement(sb, "_");
    result = m.find();
    }
    // Add the last segment of input to the new String
    m.appendTail(sb);
    System.out.println(sb.toString());
    // File (or directory) with new name
    System.out.println("entering here");
    file2 = new java.io.File(file+sb.toString());
    // Rename file (or directory)
    boolean success = file.renameTo(file2);
    if (success) {
    System.out.println("Successfully renamed !");
    boolean success1 = file.delete();
    if (success1){
    System.out.println("Successfully deleted !");
    }
    else
    System.out.println("Could not be delted!");
    // File was not successfully renamed
    }
    else{
    System.out.println("renaming failed");
    }

    }
    out = new BufferedWriter(new FileWriter(file, true));
    out.newLine();
    /* uncomment this for non-windows files*/
    //out.write("\r");
    out.write(appendValue);
    out.close();


    }catch (IOException e) { //end of try
    }
    catch(Exception e1){
    }
    finally {
    try{
    out.close();
    }catch(Exception e){
    e.printStackTrace();
    }

    }
    }catch(Exception e){
    e.printStackTrace();
    }



    }

    }
    ***********************
    The properties file :
    **********************
    filename=C://dblog
    #in bytes
    fileMaxSize=1024
    ************************
    To use it :
    *********************
    DbLog.DbLogAppend("Tested for db updateasd");
    *******************

    I would appreciate if someone has tips on improving this code.

    Rgds
     
    Buddha, Aug 9, 2007
    #8
  9. Buddha wrote:
    > I havent even tried using log4j for logging database changes ( because
    > they need to go into a different log file altogether, away from
    > application logs).


    log4j is capable of logging different output to different files.

    Arne
     
    =?ISO-8859-1?Q?Arne_Vajh=F8j?=, Aug 11, 2007
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve Flitcroft

    IE Task Bar never reaches 100%

    Steve Flitcroft, Aug 9, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    409
    Steve Flitcroft
    Aug 9, 2004
  2. pcarr01
    Replies:
    3
    Views:
    684
    Gordon Beaton
    Feb 17, 2005
  3. IchBin
    Replies:
    0
    Views:
    365
    IchBin
    May 18, 2006
  4. IchBin
    Replies:
    0
    Views:
    410
    IchBin
    May 24, 2006
  5. Stuart Clarke

    Copying files and renaming dupes

    Stuart Clarke, Apr 15, 2009, in forum: Ruby
    Replies:
    6
    Views:
    107
    Robert Klemme
    May 24, 2009
Loading...

Share This Page