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

com.crabshue.commons.file.nio.FileIOUtils Maven / Gradle / Ivy

There is a newer version: 1.1.0
Show newest version
package com.crabshue.commons.file.nio;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import java.util.List;

import com.crabshue.commons.exceptions.SystemException;
import com.crabshue.commons.file.nio.exceptions.FileErrorContext;
import com.crabshue.commons.file.nio.exceptions.FileErrorType;
import lombok.NonNull;

/**
 * Utility class for IO operations on files.
 */
public class FileIOUtils {

    /**
     * Write down a collection of lines in an output file.
     *
     * @param lines          the file in byte array
     * @param outputFilePath the output file.
     * @return the written file
     */
    public static Path writeFile(@NonNull final Collection lines,
                                 @NonNull final Path outputFilePath) {

        try {
            FileSystemUtils.retrieveOrCreateFile(outputFilePath);
            Files.write(outputFilePath, lines, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        } catch (IOException e) {
            throw new SystemException(FileErrorType.ERROR_WRITING_FILE, e)
                .addContextValue(FileErrorContext.FILE, outputFilePath);
        }
        return outputFilePath;
    }


    /**
     * Write down a byte array in an output file.
     *
     * @param bytes          the file in byte array
     * @param outputFilePath the output file.
     * @return the written file
     */
    public static Path writeFile(@NonNull final byte[] bytes,
                                 @NonNull final Path outputFilePath) {

        try {
            FileSystemUtils.retrieveOrCreateFile(outputFilePath);
            Files.write(outputFilePath, bytes, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        } catch (IOException e) {
            throw new SystemException(FileErrorType.ERROR_WRITING_FILE, e)
                .addContextValue(FileErrorContext.FILE, outputFilePath);
        }
        return outputFilePath;
    }


    /**
     * Read the content of a {@link Path file} as a collection {@link String lines}.
     *
     * @param filePath the path to a file.
     * @return the collection of lines.
     */
    public static List readLines(@NonNull final Path filePath) {

        try {
            return Files.readAllLines(filePath, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new SystemException(FileErrorType.ERROR_READING_FILE, e)
                .addContextValue(FileErrorContext.FILE, filePath);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy