Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Stream' - 59 code snippet(s) found

 Sample 1. Get count of elements greater than 1 using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use Stream, Predicate and Filter to get the count of elements more than 1

System.out.println(intSet.stream().filter(moreThan2Pred).count()); // Prints 3

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter


 Sample 2. Combine two Summaries and Generate a new Summary using Lambda Expression

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();
Set<Integer> intSet2 = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);
intSet2.add(1);
intSet2.add(2);
intSet2.add(3);
intSet2.add(4);

// Use the stream and collectors to Summarize all Integer elements

IntSummaryStatistics summary = intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)));

summary.combine(intSet2.stream().collect(Collectors.summarizingInt(p->((Integer)p))));

System.out.println(summary); // Prints IntSummaryStatistics{count=8, sum=20, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt   summary.combine  java.util.hashset  java.util.stream.Collectors  java.util.IntSummaryStatistics


 Sample 3. Get all elements greater than 2, sort them and then push them to a new set, using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Set the predicate or the condition for filtering the elements.

Predicate<Integer> moreThan2Pred = (p) -> (p > 1);

// Use Filter to refine the element set, sort to Sort and Collectors.toSet to get a set out of Stream.

intSet = intSet.stream().filter(moreThan2Pred).sorted().collect(Collectors.toSet());

System.out.println(intSet); // Prints [2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter   sort  java.util.hashset  java.util.stream.Collectors


 Sample 4. Find the Average of all collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and Collector to find the average of all elements.

System.out.println(intSet.stream().collect(Collectors.averagingInt(p->((Integer)p))));  Prints 2.5

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collector


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Group Elements by even or Odd using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and Collector to Group by Even and Odd

System.out.println(intSet.stream().collect(Collectors.groupingBy(p->((Integer)p)%2)));  Prints {0=[2, 4], 1=[1, 3]}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 6. Sum all collection elements using Lambda Expressions

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to sum all elements.

System.out.println(intSet.stream().collect(Collectors.summingInt(p->(Integer)p)));

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 7. Get the complete Summary of Collection Elements using Lambda Expressions

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to Summarize all Integer elements 

System.out.println(intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)))); // Prints IntSummaryStatistics{count=4, sum=10, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt


 Sample 8. Populate a List using Set elements and Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to get List out of Set

List li = intSet.stream().collect(Collectors.toList());
System.out.println(li); // Prints [1, 2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.toList


 Sample 9. Create a Map using Set elements using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Use the stream and collectors to get a Map out of Set 

System.out.println(intSet.stream().collect((Collectors.toMap(p->(Integer)p,q->((Integer)q)*500)))); // Prints {1=500, 2=1000, 3=1500, 4=2000} 

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Load Properties using Property Class

private static Properties props = null;
   
private static void loadProperties(){
   try {
      if(props == null || props1 == null || props2 == null){
         props = new Properties();
         props.load(new FileInputStream(Constants.PROP_BASE_DIR + Constants.EMPLOYEE_REPORTING_PROP));
      } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }
}

   Like      Feedback     property class  properties  FileInputStream  file handling


 Sample 11. Code Sample / Example / Snippet of java.util.zip.DeflaterOutputStream

    private byte[] deflate(byte[] b) throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

DeflaterOutputStream dos = new DeflaterOutputStream(baos);

dos.write(b);

dos.close();

return baos.toByteArray();

}


   Like      Feedback      java.util.zip.DeflaterOutputStream


 Sample 12. Code Sample / Example / Snippet of java.util.zip.GZIPInputStream

  private static CSVReader openCsv(File file) throws IOException {

final Reader fileReader;

if (file.getName().endsWith(".gz")) {

final GZIPInputStream inputStream =

new GZIPInputStream(new FileInputStream(file));

fileReader = new InputStreamReader(inputStream);

} else {

fileReader = new FileReader(file);

}

return new CSVReader(fileReader);

}


   Like      Feedback      java.util.zip.GZIPInputStream


 Sample 13. Code Sample / Example / Snippet of java.util.jar.JarOutputStream

    private File createBundle(String symbolicName, String version) throws IOException {

File tmpFile = File.createTempFile("tmpbundle-", "jar");

tmpFile.deleteOnExit();

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

if (symbolicName != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, symbolicName);

}

if (version != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);

}

JarOutputStream target = new JarOutputStream(new FileOutputStream(tmpFile), manifest);

target.close();

return tmpFile;

}


   Like      Feedback      java.util.jar.JarOutputStream


 Sample 14. Code Sample / Example / Snippet of java.io.FileOutputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Get the Maximum number out of the Integer List, using Lambda Expression

// Declare and Initialize the Collection

List<Integer> intList = new ArrayList<Integer>();

// Add Elements

intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);


System.out.println(intList.stream().reduce(Math::max).get()); // Prints 1

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream  reducer   Math::max


 Sample 16. Write to a file using File, FileOutputStream and ObjectOutputStream

class BuggyBread1{
   public static void main(String[] args){
      try {
         BuggyBread1 buggybread1 = new BuggyBread1();
         ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
         objectOutputStream.writeObject(buggybread1);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

   Like      Feedback     File   FileOutputStream   ObjectOutputStream   file handling


 Sample 17. Load XLS file and print first column using poi XSSFWorkbook

public XSSFWorkbook loadXLSAndPrintFirstColumn(File xlsFile) {
   InputStream inputStream = null;
   try {
      inputStream = new FileInputStream(xlsFile);
   XSSFWorkbook xssFWorkbook = new XSSFWorkbook(inputStream);
      Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
      for (int index = 0; index < sheet.getPhysicalNumberOfRows(); index++) {
      try {
         Row row = sheet.getRow(index);
            System.out.println(row.getCell(0,Row.CREATE_NULL_AS_BLANK).getStringCellValue()));   
      } catch (Exception e) {
      System.out.println("Exception");
   }
}

}

   Like      Feedback     readinf xls  reading excel  apache poi  XSSFWorkbook  InputStream


 Sample 18. Usage of java.io.FileInputStream

FileInputStream fis = new FileInputStream("mypodcast.mp3");
InputStreamRequestEntity re = new InputStreamRequestEntity(fis, "audio/mp3");

   Like      Feedback     ileInputStrea


 Sample 19. Usage of java.io.ByteArrayInputStream

ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();

   Like      Feedback     ByteArrayInputStream  java.io  input stream  ObjectInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Usage of ByteArrayOutputStream

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (Exception e) {
}

   Like      Feedback     java.io.ByteArrayOutputStream  java.io  ObjectOutputStream


 Sample 21. Usage of org.apache.hadoop.hdfs.server.namenode.FSEditLog.EditLogFileInputStream

EditLogFileInputStream edits =
new EditLogFileInputStream(getImageFile(sd, NameNodeFile.EDITS));
numEdits = FSEditLog.loadFSEdits(edits);
edits.close();
File editsNew = getImageFile(sd, NameNodeFile.EDITS_NEW);
if (editsNew.exists() && editsNew.length() > 0) {
edits = new EditLogFileInputStream(editsNew);
numEdits += FSEditLog.loadFSEdits(edits);
edits.close();

   Like      Feedback     EditLogFileInputStream  Apache Hadoop


 Sample 22. Code Sample / Example / Snippet of org.apache.hadoop.fs.FSDataInputStream

    private void init() throws IOException {

if (reader == null) {

FSDataInputStream in = fs.open(file);

in.seek(segmentOffset);

reader = new Reader<K, V>(conf, in, segmentLength, codec);

}

}


   Like      Feedback      org.apache.hadoop.fs.FSDataInputStream


 Sample 23. Concatenate two Streams

public static IntStream concat(IntStream a, IntStream b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);

Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
a.spliterator(), b.spliterator());
IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
return stream.onClose(Streams.composedClose(a, b));
}

   Like      Feedback     Concatenate two Streams   java 8  java8


 Sample 24. Code Sample / Example / Snippet of org.apache.spark.mllib.stat.test.StreamingTest

  public void streamingTest() {

List<BinarySample> trainingBatch = Arrays.asList(

new BinarySample(true, 1.0),

new BinarySample(false, 2.0));

JavaDStream<BinarySample> training =

attachTestInputStream(ssc, Arrays.asList(trainingBatch, trainingBatch), 2);

int numBatches = 2;

StreamingTest model = new StreamingTest()

.setWindowSize(0)

.setPeacePeriod(0)

.setTestMethod("welch");

model.registerStream(training);

attachTestOutputStream(training);

runStreams(ssc, numBatches, numBatches);

}


   Like      Feedback      org.apache.spark.mllib.stat.test.StreamingTest


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Code Sample / Example / Snippet of org.apache.spark.network.protocol.StreamChunkId

  public void handleSuccessfulFetch() throws Exception {

StreamChunkId streamChunkId = new StreamChunkId(1, 0);



TransportResponseHandler handler = new TransportResponseHandler(new LocalChannel());

ChunkReceivedCallback callback = mock(ChunkReceivedCallback.class);

handler.addFetchRequest(streamChunkId, callback);

assertEquals(1, handler.numOutstandingRequests());



handler.handle(new ChunkFetchSuccess(streamChunkId, new TestManagedBuffer(123)));

verify(callback, times(1)).onSuccess(eq(0), (ManagedBuffer) any());

assertEquals(0, handler.numOutstandingRequests());

}


   Like      Feedback      org.apache.spark.network.protocol.StreamChunkId


 Sample 26. Code Sample / Example / Snippet of org.apache.storm.trident.Stream

    public static StormTopology buildTopology(WindowsStoreFactory windowStore, WindowConfig windowConfig) throws Exception {

FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, new Values("the cow jumped over the moon"),

new Values("the man went to the store and bought some candy"), new Values("four score and seven years ago"),

new Values("how many apples can you eat"), new Values("to be or not to be the person"));

spout.setCycle(true);



TridentTopology topology = new TridentTopology();



Stream stream = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),

new Split(), new Fields("word"))

.window(windowConfig, windowStore, new Fields("word"), new CountAsAggregator(), new Fields("count"))

.peek(new Consumer() {

@Override

public void accept(TridentTuple input) {

LOG.info("Received tuple: [{}]", input);

}

});



return topology.build();

}


   Like      Feedback      org.apache.storm.trident.Stream


 Sample 27. Code Sample / Example / Snippet of org.apache.storm.blobstore.AtomicOutputStream

    private static void createBlobWithContent(String blobKey, ClientBlobStore clientBlobStore, File file)

throws AuthorizationException, KeyAlreadyExistsException, IOException,KeyNotFoundException {

String stringBlobACL = "o::rwa";

AccessControl blobACL = BlobStoreAclHandler.parseAccessControl(stringBlobACL);

List<AccessControl> acls = new LinkedList<AccessControl>();

acls.add(blobACL); // more ACLs can be added here

SettableBlobMeta settableBlobMeta = new SettableBlobMeta(acls);

AtomicOutputStream blobStream = clientBlobStore.createBlob(blobKey,settableBlobMeta);

blobStream.write(readFile(file).toString().getBytes());

blobStream.close();

}


   Like      Feedback      org.apache.storm.blobstore.AtomicOutputStream


 Sample 28. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

  private static Pair<SqlLine.Status, String> run(String... args)

throws Throwable {

SqlLine sqlline = new SqlLine();

ByteArrayOutputStream os = new ByteArrayOutputStream();

PrintStream sqllineOutputStream = new PrintStream(os);

sqlline.setOutputStream(sqllineOutputStream);

sqlline.setErrorStream(sqllineOutputStream);

SqlLine.Status status = SqlLine.Status.OK;



Bug.upgrade("[sqlline-35] Make Sqlline.begin public");



return Pair.of(status, os.toString("UTF8"));

}


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 29. Code Sample / Example / Snippet of javax.servlet.ServletOutputStream

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

ServletOutputStream output = null;

try {

output = response.getOutputStream();

output.println(request.getQueryString());

}

catch (IOException e) {

} finally {

if (output != null) {

try {

output.close();

}

catch (IOException e) {

}

}

}

}


   Like      Feedback      javax.servlet.ServletOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Code Sample / Example / Snippet of java.security.DigestOutputStream

    public void setUpTestCase() throws Exception {

File file = File.createTempFile("test", ".bin", new File("generated"));

file.deleteOnExit();



DigestOutputStream dos = null;

try {

dos = new DigestOutputStream(new FileOutputStream(file), MessageDigest.getInstance("MD5"));



for (int i = 0; i < 10000; i++) {

dos.write(String.valueOf(System.currentTimeMillis()).getBytes());

dos.write(" Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum Lorum Ipsum ".getBytes());

}

dos.flush();

}

finally {

if (dos != null) {

dos.close();

}

}



m_testContentURL = file.toURI().toURL();

m_contentLength = file.length();

m_digest = new String(dos.getMessageDigest().digest());

}


   Like      Feedback      java.security.DigestOutputStream


 Sample 31. Code Sample / Example / Snippet of java.security.DigestInputStream

    private String getDigest(InputStream is) throws Exception {

DigestInputStream dis = new DigestInputStream(is, MessageDigest.getInstance("MD5"));

while (dis.read() != -1) {

}

dis.close();

return new String(dis.getMessageDigest().digest());

}


   Like      Feedback      java.security.DigestInputStream


 Sample 32. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream

            public int compare(ResourceImpl r1, ResourceImpl r2) {

String s1 = getName(r1);

String s2 = getName(r2);

return s1.compareTo(s2);

}

});



Tag tag = doIndex(sorted);

if (repositoryFileName != null) {

ByteArrayOutputStream out = new ByteArrayOutputStream();


   Like      Feedback      java.io.ByteArrayOutputStream


 Sample 33. Code Sample / Example / Snippet of java.io.ByteArrayInputStream

    protected final void importSingleUser(Repository userRepository, String userName, String password) throws Exception {

ByteArrayInputStream bis = new ByteArrayInputStream((

"<roles>" +

"<user name="" + userName + "">" +

"<properties><username>" + userName + "</username></properties>" +

"<credentials><password type="String">" + password + "</password></credentials>" +

"</user>" +

"</roles>").getBytes());



Assert.assertTrue("Committing test user data failed!", userRepository.commit(bis, userRepository.getRange().getHigh()));

}


   Like      Feedback      java.io.ByteArrayInputStream


 Sample 34. Code Sample / Example / Snippet of java.io.FileInputStream

    public static void copy(File input, File output) throws IOException {

FileInputStream fis = new FileInputStream(input);

FileOutputStream fos = new FileOutputStream(output);



try {

FileChannel ic = fis.getChannel();

FileChannel oc = fos.getChannel();

try {

oc.transferFrom(ic, 0, ic.size());

}

finally {

oc.close();

ic.close();

}

}

finally {

fis.close();

fos.close();

}

}


   Like      Feedback      java.io.FileInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Code Sample / Example / Snippet of java.io.OutputStream

    public static void generateBundle(ArtifactData data, Map<String, String> additionalHeaders) throws IOException {

OutputStream bundleStream = null;

try {

File dataFile = new File(data.getUrl().toURI());

OutputStream fileStream = new FileOutputStream(dataFile);

bundleStream = new JarOutputStream(fileStream, getBundleManifest(data.getSymbolicName(), data.getVersion(), additionalHeaders));

bundleStream.flush();

} catch (URISyntaxException e) {

throw new IOException();

} finally {

if (bundleStream != null) {

bundleStream.close();

}

}

}


   Like      Feedback      java.io.OutputStream


 Sample 36. Code Sample / Example / Snippet of java.io.InputStream

    public static boolean filesDiffer(File first, File second) throws Exception {

if (first.length() != second.length()) {

return true;

}

InputStream firstStream = new FileInputStream(first);

InputStream secondStream = new FileInputStream(second);

try {

for (int i = 0; i < first.length(); i++) {

if (firstStream.read() != secondStream.read()) {

return false;

}

}

return true;

}

finally {

try {

firstStream.close();

}

finally {

secondStream.close();

}

}

}


   Like      Feedback      java.io.InputStream


 Sample 37. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveOutputStream

    protected File createEmptyArchive(final String archivename) throws Exception {

ArchiveOutputStream out = null;

OutputStream stream = null;

archiveList = new ArrayList<String>();

try {

archive = File.createTempFile("empty", "." + archivename);

archive.deleteOnExit();

stream = new FileOutputStream(archive);

out = factory.createArchiveOutputStream(archivename, stream);

out.finish();

} finally {

if (out != null) {

out.close();

} else if (stream != null) {

stream.close();

}

}

return archive;

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveOutputStream


 Sample 38. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveInputStream

    protected void checkArchiveContent(final File archive, final List<String> expected)

throws Exception {

final InputStream is = new FileInputStream(archive);

try {

final BufferedInputStream buf = new BufferedInputStream(is);

final ArchiveInputStream in = factory.createArchiveInputStream(buf);

this.checkArchiveContent(in, expected);

} finally {

is.close();

}

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveInputStream


 Sample 39. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveInputStream

    private void testZipStreamWithImplodeCompression(final String filename, final String entryName) throws IOException {

final ZipArchiveInputStream zin = new ZipArchiveInputStream(new FileInputStream(new File(filename)));

final ZipArchiveEntry entry = zin.getNextZipEntry();

assertEquals("entry name", entryName, entry.getName());

assertTrue("entry can't be read", zin.canReadEntryData(entry));

assertEquals("method", ZipMethod.IMPLODING.getCode(), entry.getMethod());



final InputStream bio = new BoundedInputStream(zin, entry.getSize());



final ByteArrayOutputStream bout = new ByteArrayOutputStream();

final CheckedOutputStream out = new CheckedOutputStream(bout, new CRC32());

IOUtils.copy(bio, out);



out.flush();



assertEquals("CRC32", entry.getCrc(), out.getChecksum().getValue());

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipArchiveInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.arj.ArjArchiveInputStream

    public void testArjUnarchive() throws Exception {

final StringBuilder expected = new StringBuilder();

expected.append("test1.xml<?xml version="1.0"?> ");

expected.append("<empty/>test2.xml<?xml version="1.0"?> ");

expected.append("<empty/> ");





final ArjArchiveInputStream in = new ArjArchiveInputStream(new FileInputStream(getFile("bla.arj")));

ArjArchiveEntry entry;



final StringBuilder result = new StringBuilder();

while ((entry = in.getNextEntry()) != null) {

result.append(entry.getName());

int tmp;

while ((tmp = in.read()) != -1) {

result.append((char) tmp);

}

assertFalse(entry.isDirectory());

}

in.close();

assertEquals(result.toString(), expected.toString());

}


   Like      Feedback      org.apache.commons.compress.archivers.arj.ArjArchiveInputStream


 Sample 41. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream

    public void testCpioUnarchive() throws Exception {

final StringBuilder expected = new StringBuilder();

expected.append("./test1.xml<?xml version="1.0"?> ");

expected.append("<empty/>./test2.xml<?xml version="1.0"?> ");

expected.append("<empty/> ");





final CpioArchiveInputStream in = new CpioArchiveInputStream(new FileInputStream(getFile("bla.cpio")));

CpioArchiveEntry entry;



final StringBuilder result = new StringBuilder();

while ((entry = (CpioArchiveEntry) in.getNextEntry()) != null) {

result.append(entry.getName());

int tmp;

while ((tmp = in.read()) != -1) {

result.append((char) tmp);

}

}

in.close();

assertEquals(result.toString(), expected.toString());

}


   Like      Feedback      org.apache.commons.compress.archivers.cpio.CpioArchiveInputStream


 Sample 42. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.ArchiveStreamFactory

    public void testEncodingCtor() {

ArchiveStreamFactory fac = new ArchiveStreamFactory();

assertNull(fac.getEntryEncoding());

fac = new ArchiveStreamFactory(null);

assertNull(fac.getEntryEncoding());

fac = new ArchiveStreamFactory("UTF-8");

assertEquals("UTF-8", fac.getEntryEncoding());

}


   Like      Feedback      org.apache.commons.compress.archivers.ArchiveStreamFactory


 Sample 43. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorStreamFactory

    public void testOverride() {

CompressorStreamFactory fac = new CompressorStreamFactory();

assertFalse(fac.getDecompressConcatenated());

fac.setDecompressConcatenated(true);

assertTrue(fac.getDecompressConcatenated());



fac = new CompressorStreamFactory(false);

assertFalse(fac.getDecompressConcatenated());

try {

fac.setDecompressConcatenated(true);

fail("Expected IllegalStateException");

} catch (final IllegalStateException ise) {

}



fac = new CompressorStreamFactory(true);

assertTrue(fac.getDecompressConcatenated());

try {

fac.setDecompressConcatenated(true);

fail("Expected IllegalStateException");

} catch (final IllegalStateException ise) {

}

}


   Like      Feedback      org.apache.commons.compress.compressors.CompressorStreamFactory


 Sample 44. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorInputStream

    public void testBzip2Unarchive() throws Exception {

final File input = getFile("bla.txt.bz2");

final File output = new File(dir, "bla.txt");

final InputStream is = new FileInputStream(input);

final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);

final FileOutputStream os = new FileOutputStream(output);

IOUtils.copy(in, os);

is.close();

os.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.CompressorInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream

    private void testExtraFlags(final int compressionLevel, final int flag) throws Exception {

final FileInputStream fis = new FileInputStream(getFile("test3.xml"));

byte[] content;

try {

content = IOUtils.toByteArray(fis);

} finally {

fis.close();

}



final ByteArrayOutputStream bout = new ByteArrayOutputStream();



final GzipParameters parameters = new GzipParameters();

parameters.setCompressionLevel(compressionLevel);

final GzipCompressorOutputStream out = new GzipCompressorOutputStream(bout, parameters);

IOUtils.copy(new ByteArrayInputStream(content), out);

out.flush();

out.close();



assertEquals("extra flags (XFL)", flag, bout.toByteArray()[8]);

}


   Like      Feedback      org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream


 Sample 46. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveInputStream

    public void readSimplePaxHeader() throws Exception {

final InputStream is = new ByteArrayInputStream(new byte[1]);

final TarArchiveInputStream tais = new TarArchiveInputStream(is);

final Map<String, String> headers = tais

.parsePaxHeaders(new ByteArrayInputStream("30 atime=1321711775.972059463 "

.getBytes(CharsetNames.UTF_8)));

assertEquals(1, headers.size());

assertEquals("1321711775.972059463", headers.get("atime"));

tais.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.tar.TarArchiveInputStream


 Sample 47. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream

    public void readOfLength0ShouldReturn0() throws Exception {

final byte[] rawData = new byte[1048576];

for (int i=0; i < rawData.length; ++i) {

rawData[i] = (byte) Math.floor(Math.random()*256);

}



final ByteArrayOutputStream baos = new ByteArrayOutputStream();

final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);

bzipOut.write(rawData);

bzipOut.flush();

bzipOut.close();

baos.flush();

baos.close();



final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);

final byte[] buffer = new byte[1024];

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

bzipIn.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream


 Sample 48. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BitInputStream

    public void testClearBitCache() throws IOException {

final BitInputStream bis = new BitInputStream(getStream(), ByteOrder.LITTLE_ENDIAN);

assertEquals(0x08, bis.readBits(4));

bis.clearBitCache();

assertEquals(0, bis.readBits(1));

bis.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BitInputStream


 Sample 49. Code Sample / Example / Snippet of org.apache.commons.compress.utils.BoundedInputStream

    public void writeTo(final ZipArchiveOutputStream target) throws IOException {

backingStore.closeForWriting();

final InputStream data = backingStore.getInputStream();

for (final CompressedEntry compressedEntry : items) {

final BoundedInputStream rawStream = new BoundedInputStream(data, compressedEntry.compressedSize);

target.addRawArchiveEntry(compressedEntry.transferToArchiveEntry(), rawStream);

rawStream.close();

}

data.close();

}


   Like      Feedback      org.apache.commons.compress.utils.BoundedInputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream

    public void testCompressionMethod() throws Exception {

final ZipArchiveOutputStream zos =

new ZipArchiveOutputStream(new ByteArrayOutputStream());

final ZipArchiveEntry entry = new ZipArchiveEntry("foo");

assertEquals(-1, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.STORED);

assertEquals(ZipEntry.STORED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(ZipEntry.DEFLATED);

assertEquals(ZipEntry.DEFLATED, entry.getMethod());

assertTrue(zos.canWriteEntryData(entry));



entry.setMethod(6);

assertEquals(6, entry.getMethod());

assertFalse(zos.canWriteEntryData(entry));

zos.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream


 Sample 51. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.tar.TarArchiveOutputStream

    public void shouldUseSpecifiedEncodingWhenReadingGNULongNames()

throws Exception {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final String encoding = CharsetNames.UTF_16;

final String name = "1234567890123456789012345678901234567890123456789"

+ "01234567890123456789012345678901234567890123456789"

+ "01234567890u00e4";

final TarArchiveOutputStream tos =

new TarArchiveOutputStream(bos, encoding);

tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

TarArchiveEntry t = new TarArchiveEntry(name);

t.setSize(1);

tos.putArchiveEntry(t);

tos.write(30);

tos.closeArchiveEntry();

tos.close();

final byte[] data = bos.toByteArray();

final ByteArrayInputStream bis = new ByteArrayInputStream(data);

final TarArchiveInputStream tis =

new TarArchiveInputStream(bis, encoding);

t = tis.getNextTarEntry();

assertEquals(name, t.getName());

tis.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.tar.TarArchiveOutputStream


 Sample 52. Code Sample / Example / Snippet of org.apache.commons.compress.archivers.dump.DumpArchiveInputStream

    public void testConsumesArchiveCompletely() throws Exception {

final InputStream is = DumpArchiveInputStreamTest.class

.getResourceAsStream("/archive_with_trailer.dump");

final DumpArchiveInputStream dump = new DumpArchiveInputStream(is);

while (dump.getNextDumpEntry() != null) {

}

final byte[] expected = new byte[] {

'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', ' '

};

final byte[] actual = new byte[expected.length];

is.read(actual);

assertArrayEquals(expected, actual);

dump.close();

}


   Like      Feedback      org.apache.commons.compress.archivers.dump.DumpArchiveInputStream


 Sample 53. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream

    public void readOfLength0ShouldReturn0() throws Exception {

final byte[] rawData = new byte[1048576];

for (int i=0; i < rawData.length; ++i) {

rawData[i] = (byte) Math.floor(Math.random()*256);

}



final ByteArrayOutputStream baos = new ByteArrayOutputStream();

final BZip2CompressorOutputStream bzipOut = new BZip2CompressorOutputStream(baos);

bzipOut.write(rawData);

bzipOut.flush();

bzipOut.close();

baos.flush();

baos.close();



final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

final BZip2CompressorInputStream bzipIn = new BZip2CompressorInputStream(bais);

final byte[] buffer = new byte[1024];

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

Assert.assertEquals(0, bzipIn.read(buffer, 1024, 0));

Assert.assertEquals(1024, bzipIn.read(buffer, 0, 1024));

bzipIn.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream


 Sample 54. Code Sample / Example / Snippet of org.apache.commons.compress.utils.CountingOutputStream

    public void output() throws Exception {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final CountingOutputStream o = new CountingOutputStream(bos);

o.write(1);

assertEquals(1, o.getBytesWritten());

o.write(new byte[] { 2, 3 });

assertEquals(3, o.getBytesWritten());

o.write(new byte[] { 2, 3, 4, 5, }, 2, 1);

assertEquals(4, o.getBytesWritten());

o.count(-1);

assertEquals(4, o.getBytesWritten());

o.count(-2);

assertEquals(2, o.getBytesWritten());

o.close();

assertArrayEquals(new byte[] { 1, 2, 3, 4 }, bos.toByteArray());

}


   Like      Feedback      org.apache.commons.compress.utils.CountingOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 55. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream

    public void testRemainingChunkTypes() throws Exception {

final FileInputStream isSz = new FileInputStream(getFile("mixed.txt.sz"));

final ByteArrayOutputStream out = new ByteArrayOutputStream();

try {

final FramedSnappyCompressorInputStream in = new FramedSnappyCompressorInputStream(isSz);

IOUtils.copy(in, out);

out.close();

} finally {

isSz.close();

}



assertArrayEquals(new byte[] { '1', '2', '3', '4',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9',

'5', '6', '7', '8', '9', 10,

'1', '2', '3', '4',

'1', '2', '3', '4',

}, out.toByteArray());

}


   Like      Feedback      org.apache.commons.compress.compressors.snappy.FramedSnappyCompressorInputStream


 Sample 56. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream

    public void availableShouldReturnNonZero() throws IOException {

final File input = AbstractTestCase.getFile("bla.tar.deflatez");

final InputStream is = new FileInputStream(input);

try {

final DeflateCompressorInputStream in =

new DeflateCompressorInputStream(is);

Assert.assertTrue(in.available() > 0);

in.close();

} finally {

is.close();

}

}


   Like      Feedback      org.apache.commons.compress.compressors.deflate.DeflateCompressorInputStream


 Sample 57. Code Sample / Example / Snippet of org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream

    public void canReadASingleByteFlushAndFinish() throws IOException {

final ByteArrayOutputStream bos = new ByteArrayOutputStream();

final DeflateCompressorOutputStream cos = new DeflateCompressorOutputStream(bos);

cos.write(99);

cos.flush();

cos.finish();

Assert.assertTrue(bos.toByteArray().length > 0);

cos.close();

}


   Like      Feedback      org.apache.commons.compress.compressors.deflate.DeflateCompressorOutputStream


 Sample 58. GunZip file using Apache Commons


   public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
try {
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
try {
IOUtils.copy(new FileInputStream(input), cos);
} finally {
cos.close();
}
} finally {
out.close();
}
}

   Like      Feedback     Zip file using Apache Commons   Compress file using Apache Commons   GunZip file using Apache Commons  Code Sample / Example / Snippet of org.apache.commons.compress.compressors.CompressorOutputStream  IOUtils.copy


 Sample 59. Usage of java.util.stream.Stream

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(4, 5);

Stream.of(list1, list1)
.flatMap(list -> list.stream())
.forEach(System.out::println);

   Like      Feedback     Stream.flatMap  System.out::println



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner