blog-software-java/src/main/java/eu/m724/blog/compress/CommonsCompressor.java
Minecon724 62eb9903c0
Refactoring, more abstraction
Signed-off-by: Minecon724 <git@m724.eu>
2025-03-10 17:50:47 +01:00

58 lines
2.2 KiB
Java

/*
* Copyright (c) 2025 blog-software-java developers
* blog-software-java is licensed under the GNU General Public License. See the LICENSE.md file
* in the project root for the full license text.
*/
package eu.m724.blog.compress;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CommonsCompressor extends FileCompressor {
/**
* Constructs a {@link FileCompressor} instance using the provided algorithm.
*
* @param algorithm The algorithm, for valid names see {@link CompressorStreamFactory}
* @throws NoSuchAlgorithmException If that algorithm is unavailable or the name is invalid.
*/
public CommonsCompressor(String algorithm) throws NoSuchAlgorithmException {
super(algorithm);
try {
var os = new CompressorStreamFactory().createCompressorOutputStream(algorithm, OutputStream.nullOutputStream());
os.close();
} catch (NoClassDefFoundError | CompressorException e) {
throw new NoSuchAlgorithmException(algorithm, e);
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException closing test output stream", e);
}
}
@Override
public void compress(Path file) throws IOException, CompressException {
var destination = file.resolveSibling(file.getFileName() + "." + getAlgorithmName());
compress(file, destination);
}
@Override
public void compress(Path source, Path destination) throws IOException, CompressException {
if (Files.exists(destination))
throw new FileAlreadyExistsException(destination.toString());
try (
var outputStream = new CompressorStreamFactory()
.createCompressorOutputStream(getAlgorithmName(), Files.newOutputStream(destination))
) {
Files.copy(source, outputStream);
} catch (CompressorException e) {
throw new CompressException(e);
}
}
}