All Downloads are FREE. Search and download functionalities are using the official Maven repository.

work.eddiejamsession.file.utils.FileUtils Maven / Gradle / Ivy

There is a newer version: 0.14.3
Show newest version
package work.eddiejamsession.file.utils;


import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

import static org.apache.commons.io.FileUtils.readFileToString;
import static org.apache.commons.io.FileUtils.writeStringToFile;
import static work.eddiejamsession.exception.utils.ExceptionUtils.gag;
import static work.eddiejamsession.exception.utils.ExceptionUtils.toss;

public class FileUtils {
    public static final Charset UTF_16 = StandardCharsets.UTF_16;
    //public api

    public static void createIfNotExists(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            gag(() -> mkdirs(file));
            toss(file::createNewFile);
        }
    }

    private static boolean mkdirs(File file) {
        File parentFile = file.getParentFile();
        return !Objects.isNull(parentFile) && parentFile.mkdirs();
    }

    public static byte[] computeIfAbsentBytes(String fileName, Supplier data) {
        return Base64.getDecoder().decode(computeIfAbsent(fileName, () -> Base64.getEncoder().encodeToString(data.get())));
    }

    public static Optional getData(String fileName) {
        return toss(() -> {
            File file = new File(fileName);
            createIfNotExists(fileName);
            String strip = readFileToString(file, UTF_16).trim();
            if (strip.trim().isEmpty()) {
                return Optional.empty();
            } else {
                return Optional.of(strip);
            }
        });
    }

    public static String computeIfAbsent(String fileName, Supplier stringData) {
        return toss(() -> {
            File file = new File(fileName);
            createIfNotExists(fileName);
            String strip;
            strip = readFileToString(file, UTF_16).trim();
            if (strip.isEmpty()) {
                String d = stringData.get();
                writeToFile(fileName, d);
                return d;
            } else {
                return strip;
            }
        });
    }

    public static void writeToFile(String fileName, String data) {
        toss(() -> {
            createAndWrite(fileName, data);
        });
    }

    private static void createAndWrite(String fileName, String data) throws IOException {
        createIfNotExists(fileName);
        writeStringToFile(new File(fileName), data, UTF_16);
    }
///--
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy