Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.util.logging check if file exist in java

Tags:

java

file

logging

I am using java's java.util.logging api for logging messages in my java application.as of now each time file is getting created when application starts. i want to check if file exist then append content to that file

code :

public static Logger logger;
static FileHandler fh;

logger = Logger.getLogger("Log");
logger.setUseParentHandlers(false);     

String sFileName = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());

fh = new FileHandler(sPath + "//" + sFileName + ".txt");
logger.addHandler(fh);

SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);

after this i called below line to get message into .txt file

Classname.logger.info("---START LOGGING----");

As my code does not use file.open() method, i cant go for file.exists() call.

like image 248
Shaggy Avatar asked May 20 '26 05:05

Shaggy


1 Answers

The FileHandler has an option to append to the given file instead of overwriting it.

FileHandler(String pattern, boolean append)
    Initialize a FileHandler to write to the given filename, with optional append.

So your code would look like this:

public static Logger logger;
static FileHandler fh;

logger = Logger.getLogger("Log");
logger.setUseParentHandlers(false);     

String sFileName = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());

fh = new FileHandler(sPath + "//" + sFileName + ".txt", true);
logger.addHandler(fh);

SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
like image 76
Fabian Ritzmann Avatar answered May 21 '26 20:05

Fabian Ritzmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!