Posts

Showing posts from October, 2021

Create a File logging Utility using Java Code

Image
  Many times during coding, we need to log our outputs or comments. Usual way to do that is to print the log on the Console using System.out.println() function.  However, there can be a requirement to print the output or comments to a file so that it can be referenced later. One option is to use log4j library which is a standard logging utility.  However, you can also create your own utility using a few lines of Java Code! Let's check out how.  We'll try to cover the following utilities which can form the base of a logging tool: 1. File logging by passing the value and the file path. 2. File logging by passing the value and setting the log path in a properties file.  3. Clear the log file.  Let's first take a look at a basic File logging utility.  1. File logging by passing the value and the file path. /**  * Writes data/logs to a file. We'll pass both the filePath where the log needs to be written, and the fileValue which needs to be written.  *  * @author computeng

Find the file size using Java code (Bytes, KB, MB and GB)

Image
  There are multiple instances when you want to find out or display the size of a file. It can be for filtering out files of certain file sizes or limit the upload size of a file. For that purpose, we'll have to find out the file size.  We'll utilize an inbuilt function which returns the size in bytes, and we'll write our own functions to find out file sizes in KB, MB and GB i.e. KiloBytes, MegaBytes, and GigaBytes. The function that we'll be using is file.length(). Now for the implementation. If you want to display the file size, the String format is more suitable.  /**  * Get File size in GB  * @author computengine.com  * @param file  * @return  */ public static String getFileSizeGigaBytes ( File file ) { return Double . toString ( ( double ) file . length ( ) / ( 1024 * 1024 * 1024 ) ) ; } /**  * Get File size in MB  * @author computengine.com  * @param file  * @return  */ public static String getFileSizeMegaBytes ( File file ) {