GzipEncoder implements Runnable { @Override public void run() { try { FileInputStream fileInputStream = new FileInputStream(sourceFile); try { FileOutputStream fileOutputStream = new FileOutputStream(targetFile); try { GZIPOutputStream gzipOutputStream = new GZIPOutputStream(fileOutputStream, BUFFER_SIZE); try { byte[] buffer = new byte[BUFFER_SIZE]; int count; while ((count = fileInputStream.read(buffer)) >= 0) { gzipOutputStream.write(buffer, 0, count); } } finally { gzipOutputStream.close(); } } finally { fileOutputStream.close(); } } finally { fileInputStream.close(); } if (!sourceFile.delete()) { InternalLogger.log(Level.WARN, "Failed to delete original log file '" + sourceFile + "'"); } } catch (IOException ex) { InternalLogger.log(Level.ERROR, ex, "Failed to compress log file '" + sourceFile + "'"); } } GzipEncoder(final File file); @Override void run();  }
@Test public void encodeExistingFile() throws IOException { String originalText = "Hello tinylog! This is some flavor text."; File originalFile = folder.newFile(); File compressedFile = new File(originalFile.getAbsolutePath() + ".gz"); Files.write(originalFile.toPath(), originalText.getBytes(StandardCharsets.UTF_8)); new GzipEncoder(originalFile).run(); assertThat(compressedFile).isFile(); assertThat(originalFile).doesNotExist(); try (InputStream fileStream = new FileInputStream(compressedFile)) { try (GZIPInputStream gzipStream = new GZIPInputStream(fileStream)) { String uncompressedText = new String(gzipStream.readAllBytes(), StandardCharsets.UTF_8); assertThat(uncompressedText).isEqualTo(originalText); } } }
@Test public void reportNonExistingFile() throws IOException { File file = folder.newFile(); Files.delete(file.toPath()); new GzipEncoder(file).run(); assertThat(systemStream.consumeErrorOutput()) .containsOnlyOnce("ERROR") .contains(file.getAbsolutePath()); }
@Test public void reportUndeletableFile() throws IOException { File file = spy(folder.newFile()); Files.write(file.toPath(), "Test".getBytes(StandardCharsets.UTF_8)); doReturn(false).when(file).delete(); new GzipEncoder(file).run(); assertThat(systemStream.consumeErrorOutput()) .containsOnlyOnce("WARN") .containsOnlyOnce("delete") .contains(file.getAbsolutePath()); }