Skip to content

Commit

Permalink
Added IOUtils.toByteArray with generator
Browse files Browse the repository at this point in the history
  • Loading branch information
ymenager committed Jan 27, 2018
1 parent 8f0b1d3 commit 9d920f2
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
11 changes: 11 additions & 0 deletions core/src/main/java/com/kloudtek/util/io/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ public static byte[] toByteArray(InputStream inputStream) throws IOException {
return buffer.toByteArray();
}

public static byte[] toByteArray(DataGenerator dataGenerator) throws IOException {
ByteArrayDataOutputStream buffer = new ByteArrayDataOutputStream();
dataGenerator.generateData(buffer);
close(buffer);
return buffer.toByteArray();
}

public static long copy(final InputStream inputStream, final OutputStream outputStream) throws IOException {
return copy(inputStream, outputStream, DEF_BUFF_SIZE);
}
Expand Down Expand Up @@ -109,4 +116,8 @@ public static byte[] toByteArray(File file) throws IOException {
public static void write(File file, byte[] data) throws IOException {
FileUtils.write(file,data);
}

public interface DataGenerator {
void generateData(OutputStream os) throws IOException;
}
}
24 changes: 24 additions & 0 deletions core/src/test/java/com/kloudtek/util/io/IOUtilsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.kloudtek.util.io;

import com.kloudtek.util.StringUtils;
import org.junit.Test;

import java.io.IOException;
import java.io.OutputStream;

import static org.junit.Assert.*;

public class IOUtilsTest {
public static final byte[] TESTDATA = StringUtils.utf8("foo");

@Test
public void toByteArrayWithGenerator() throws IOException {
byte[] data = IOUtils.toByteArray(new IOUtils.DataGenerator() {
@Override
public void generateData(OutputStream os) throws IOException {
os.write(TESTDATA);
}
});
assertArrayEquals(TESTDATA,data);
}
}

0 comments on commit 9d920f2

Please sign in to comment.