Skip to content

Commit c5415ee

Browse files
eaudetecheyne
authored andcommitted
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
1 parent c65180c commit c5415ee

File tree

3 files changed

+62
-2
lines changed

3 files changed

+62
-2
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package org.baeldung.java.io;
2+
3+
4+
import com.google.common.io.ByteStreams;
5+
import org.apache.commons.io.IOUtils;
6+
import org.junit.jupiter.api.Test;
7+
8+
import java.io.File;
9+
import java.io.FileInputStream;
10+
import java.io.IOException;
11+
import java.nio.ByteBuffer;
12+
import java.nio.channels.ReadableByteChannel;
13+
14+
import static org.junit.jupiter.api.Assertions.assertEquals;
15+
16+
class InputStreamToByteBufferUnitTest {
17+
18+
@Test
19+
public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
20+
File inputFile = getFile();
21+
ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length());
22+
FileInputStream in = new FileInputStream(inputFile);
23+
in.getChannel().read(bufferByte);
24+
25+
assertEquals(bufferByte.position(), inputFile.length());
26+
}
27+
28+
@Test
29+
public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
30+
File inputFile = getFile();
31+
ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length());
32+
ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel();
33+
IOUtils.readFully(readableByteChannel, bufferByte);
34+
35+
assertEquals(bufferByte.position(), inputFile.length());
36+
}
37+
38+
@Test
39+
public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException {
40+
File inputFile = getFile();
41+
FileInputStream in = new FileInputStream(inputFile);
42+
byte[] targetArray = ByteStreams.toByteArray(in);
43+
ByteBuffer bufferByte = ByteBuffer.wrap(targetArray);
44+
bufferByte.rewind();
45+
while (bufferByte.hasRemaining()) {
46+
bufferByte.get();
47+
}
48+
49+
assertEquals(bufferByte.position(), inputFile.length());
50+
}
51+
52+
private File getFile() {
53+
ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader();
54+
55+
String fileName = "frontenac-2257154_960_720.jpg";
56+
57+
return new File(classLoader.getResource(fileName).getFile());
58+
}
59+
60+
}
Loading

parent-java/pom.xml

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
</dependencies>
2525

2626
<properties>
27-
<guava.version>22.0</guava.version>
27+
<guava.version>23.0</guava.version>
2828
</properties>
2929

30-
</project>
30+
</project>

0 commit comments

Comments
 (0)