Get file size efficiently in Java (#14970)

* Get file size efficiently in Java

* Get file size efficiently in Java

* Get file size efficiently in Java

* Update FileSizeBenchmark.java
This commit is contained in:
Michael Olayemi
2023-10-19 12:15:54 +00:00
committed by GitHub
parent ec26c2802c
commit 3178d8cb59
2 changed files with 90 additions and 0 deletions
@@ -3,7 +3,10 @@ package com.baeldung.size;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -62,4 +65,24 @@ public class JavaFileSizeUnitTest {
final long length = file.length();
return length;
}
@Test
public void whenGetFileSizeUsingFileInputStream_thenCorrect() throws IOException {
try (FileInputStream fis = new FileInputStream(filePath)) {
long result = fis.getChannel().size();
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, result);
}
}
@Test
public void whenGetFileSizeUsingUrlAndInputStream_thenCorrect() throws IOException {
File file = new File(filePath);
URL url = file.toURI().toURL();
try (InputStream stream = url.openStream()) {
assertEquals(EXPECTED_FILE_SIZE_IN_BYTES, stream.available());
}
}
}