file


Java: Given a path to a file, create the folders to it

Assuming you have a full path to a file you want to create but the folder to it might exist or not, you can use the following code in your program to check if the folder exists and if it doesn’t, create it.

//The file we want to create;
final String logFileName = "./someFolder/anotherFolder/etc/myFile.txt";
//We find the last occurrence of the File.separator value, which will allow us to separate the path from the filename
final int lastIndex = logFileName.lastIndexOf(File.separator);
//The actual path we want to make sure it exists
final String dirPath = logFileName.substring(0, lastIndex > 0 ? lastIndex : logFileName.length());
//We try to use the folder by assigning it to a File object
final File theDir = new File(dirPath);
//Make the check that the folder exists
if (!theDir.exists()) {
    //If the folder does not exist, create it
    theDir.mkdirs();
}
//Continue with execution

Bash: Determine state of file

Following you will find some tests one can perform on a file to identify its state

Check if file $FILE does not exist

if [ ! -f "$FILE" ]; then
    echo "File $FILE does not exist";
fi

Check if file $FILE exists and is a directory

if [ -d "$FILE" ]; then
    echo "File $FILE exists and is a directory";
fi

Check if file $FILE exists and is a regular file (not a directory)

if [ -f "$FILE" ]; then
    echo "File $FILE exists and is a regular file (not a directory)";
fi

Check if file $FILE exists, we do not know what type it is (if it is a directory, socket, node, etc.)

if [ -e "$FILE" ]; then
    echo "File $FILE exists, we do not know what type it is (if it is a directory, socket, node, etc.)";
fi

Check if file $FILE exists and is a symbolic link

if [ -L "$FILE" ]; then
    echo "File $FILE exists and is a symbolic link";
fi

Check if file $FILE exists and is a socket

if [ -S "$FILE" ]; then
    echo "File $FILE exists and is a socket";
fi

Check if file $FILE exists and is not empty

if [ -s "$FILE" ]; then
    echo "File $FILE exists and is not empty";
fi

Check if file $FILE exists and is readable

if [ -r "$FILE" ]; then
    echo "File $FILE exists and is readable";
fi

Check if file $FILE exists and is writable

if [ -w "$FILE" ]; then
    echo "File $FILE exists and is writable";
fi

Check if file $FILE exists and is executable

if [ -x "$FILE" ]; then
    echo "File $FILE exists and is executable";
fi