简体   繁体   中英

java.util.logging check if file exist in java

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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