VOOZH about

URL: https://www.javacodegeeks.com/2014/04/how-to-process-stream-and-read-text-file-in-java-8.html

⇱ How to process stream and read text file in Java 8


I have converted one of my old utility class using latest Java8. I use this often to print content of manifest file to check any mysterious jar file for version etc. Just run “java ztools.PrintJar /path/to/my.jar” to see output. In the new code, you will see how I use the Java 8 stream processing to filter what I need from an Enumeration list, and then get the optional result if there is any. And then the BufferedReader now comes with “lines()” method that also do streaming. It’s pretty cool to see Java 8 in actions!
 
 
 
 
 

package ztools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Print text based resource file inside a jar file. (eg: META-INF/MANIFEST.MF)
 * @author Zemian Deng
 */
public class PrintJar {
 public static void main(String[] args) throws Exception {
 // Search given name in a jar
 JarFile jarFile = new JarFile(args[0]);
 final String searchName = (args.length >= 2) ? args[1] : "META-INF/MANIFEST.MF";
 Optional<JarEntry> searchResult = jarFile
 .stream()
 .filter(e -> e.getName().equals(searchName))
 .findFirst();
 if (!searchResult.isPresent())
 throw new RuntimeException(searchName + " not found!");
 
 // Print the JarEntry
 JarEntry entry = searchResult.get();
 try (InputStream instream = jarFile.getInputStream(entry)) {
 BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
 reader.lines().forEach(line -> System.out.println(line));
 }
 }
}
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
Java 8
👁 Photo of Zemian Deng
Zemian Deng
April 4th, 2014Last Updated: April 3rd, 2014
2 107 1 minute read
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Synther
12 years ago

Last line could be
reader.lines().forEach(System.out::println);

0
Reply
amr
11 years ago

filter(e -> e.getName().equals(searchName))

“->” what actually that meaning in java??

0
Reply
Back to top button
Close
wpDiscuz