Java Stream: File Operation

In this section, we see how to utilize Java stream in file I/O operation. 

1. File Read Operation

Let’s understand file read operation through the given example

Java
// Java Program to demonstrate
// File Read Operation
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class GFG {
    // Method to filter strings of a given length and
    // convert them to uppercase
    private static List<String>
    filterAndConvertToUpper(Stream<String> stream,
                            int length)
    {
        return stream.filter(s -> s.length() == length)
            .map(String::toUpperCase)
            .collect(Collectors.toList());
    }

    public static void main(String[] args)
    {
        // Replace with the
        // actual file path
        String fileName = "path/to/your/file.txt";

        // Step 1: Create a Stream of lines from the
        // file
        try (Stream<String> lines
             = Files.lines(Paths.get(fileName))) {

            List<String> filteredStrings
                = filterAndConvertToUpper(lines, 5);
            System.out.println(
                "Filtered strings with length 5 (converted to uppercase): "
                + filteredStrings);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Input:

Geeks
gfg
geeks
w3wiki
Coder
Guys

Output:

Filtered strings with length 5 (converted to uppercase): [GEEKS, GEEKS, CODER]

2. File Write Operation

Let’s understand file write operation through the given example

Java
// Java Program to demonstrate
// File Write Operation
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

// Driver Class
class GFG {
    // main function
    public static void main(String[] args)
    {
        String[] words
            = { "Geeks", "for", "Geeks", "Hello", "World" };

        // Replace with the
        // actual file path

        String fileName = "path/to/your/file.txt";

        // Step 1: Create a PrintWriter to write to the
        // file
        try (PrintWriter pw
             = new PrintWriter(Files.newBufferedWriter(
                 Paths.get(fileName)))) {

            // Step 2: Use Stream to write each word to the
            // file
            Stream.of(words).forEach(pw::println);

            // Step 3: Print success message to the console
            System.out.println(
                "Words written to the file successfully.");
        }
        catch (IOException e) {
            // Step 4: Handle any IO exception that occurs
            // during the file writing process
            e.printStackTrace();
        }
    }
}

Output:

Words written to the file successfully.

Java 8 Stream Tutorial

Java 8 introduces Stream, which is a new abstract layer, and some new additional packages in Java 8 called java.util.stream. A Stream is a sequence of components that can be processed sequentially. These packages include classes, interfaces, and enum to allow functional-style operations on the elements.

The stream can be used by importing java.util.stream package. Stream API is used to process collections of objects. Streams are designed to be efficient and can support improving your program’s performance by allowing you to avoid unnecessary loops and iterations. Streams can be used for filtering, collecting, printing, and converting from one data structure to another, etc. 

This Java 8 Stream Tutorial will cover all the basic to advanced concepts of Java 8 stream like Java 8 filter and collect operations, and real-life examples of Java 8 streams.

Similar Reads

Prerequisites for Java Stream

Before proceeding to Java 8, it’s recommended to have a basic knowledge of Java 8 and its important concepts such as lambda expression, Optional, method references, etc....

Features of Java Stream

A stream is not a data structure instead it takes input from the Collections, Arrays, or I/O channels.Streams don’t change the original data structure, they only provide the result as per the pipelined methods.Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result....

How does Stream Work Internally?

In streams,...

Various Core Operations Over Streams

There are broadly 3 types of operations that are carried over streams namely as follows as depicted from the image shown above:...

Lazy Evaluation

Lazy Evaluation is the concept in Java Streams where computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. It is called lazy because intermediate operations are not evaluated unless a terminal operation is invoked....

Java Stream: Real-life Examples

Example 1:...

Java Stream Operations

Method Types and Pipelines...

Terminal Operations

These are the operations that after consumed can’t further be used. There are few operations mentioned below:...

Intermediate Operations

It returns a new stream that can be further processed. There are certain operations mentioned below:...

Java Stream Specializations

As there are primitive data types or specializations like int, long and double. Similarly, streams have IntStream, LongStream, and DoubleStream. These are convenient for making performing transactions with numerical primitives....

Parallel Streams

Parallel Streams are the type of streams that can perform operations concurrently on multiple threads. These Streams are meant to make use of multiple processors or cores available to speed us the processing speed. There are two methods to create parallel streams are mentioned below:...

Infinite Streams

Infinite Streams are the type of Streams that can produce unbounded(Infnite) number of elements. These Streams are useful when you need to work with the data sources that are not finite....

Java Stream: File Operation

In this section, we see how to utilize Java stream in file I/O operation....

Java Streams Improvements in Java 9

As we know, Java 8 introduced a Java stream to the world which provided a powerful way to process collections of data. However, the following version of the language also contributed to the feature. Thereafter, some improvements and features were added to the Java stream in JAVA 9. In this section, we will provide an overview of the advancements introduced by Java 9 to the Streams API like takeWhile, dropWhile, iterate, ofNullable, etc....

Conclusion

Java Streams offer a powerful way to handle data in Java. They allow developers to write more readable and concise code for processing collections. By using Java Streams, you can easily filter, map, and reduce data with simple and expressive methods. This not only makes your code easier to maintain but also helps improve performance by taking advantage of parallel processing. If you’re looking to make your data operations more efficient and straightforward, learning Java Streams is definitely worth the effort....

Java 8 Stream – FAQs

1. How to learn streams in Java 8?...