BAEL-2059

* New section in InputStream to byte array article and recreating branch.

* Minor typo

* Code reformat using intellij formatter.

* Code reformat using intellij formatter.

* guava implementation to be completed

* guava implementation

* Added assert to guava test

* Fix formatting
This commit is contained in:
Erick Audet M.Sc 2019-01-10 17:16:53 -05:00 committed by Emily Cheyne
parent c65180c74f
commit c5415eecac
3 changed files with 62 additions and 2 deletions

View File

@ -0,0 +1,60 @@
package org.baeldung.java.io;
import com.google.common.io.ByteStreams;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InputStreamToByteBufferUnitTest {
@Test
public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length());
FileInputStream in = new FileInputStream(inputFile);
in.getChannel().read(bufferByte);
assertEquals(bufferByte.position(), inputFile.length());
}
@Test
public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length());
ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel();
IOUtils.readFully(readableByteChannel, bufferByte);
assertEquals(bufferByte.position(), inputFile.length());
}
@Test
public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
File inputFile = getFile();
FileInputStream in = new FileInputStream(inputFile);
byte[] targetArray = ByteStreams.toByteArray(in);
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
bufferByte.rewind();
while (bufferByte.hasRemaining()) {
bufferByte.get();
}
assertEquals(bufferByte.position(), inputFile.length());
}
private File getFile() {
ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader();
String fileName = "frontenac-2257154_960_720.jpg";
return new File(classLoader.getResource(fileName).getFile());
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

View File

@ -24,7 +24,7 @@
</dependencies>
<properties>
<guava.version>22.0</guava.version>
<guava.version>23.0</guava.version>
</properties>
</project>
</project>