Home > Java > javaTutorial > body text

Tips for Using Java Streams for File Input/Output

PHPz
Release: 2024-07-21 15:06:38
Original
886 people have browsed it

What is Java Input/Output?

Java Input/Output (I/O) is used to process input and generate output in the form of files. Java uses the concept of streams, which allows for fast I/O operations.
With the java.io package, all input and output operations can be easily performed.

Handling Files in Java Using Input/Output

Streams

Streams can be defined as a sequence of data composed of bytes. It's called a stream because it is like a stream of water that continues to flow. There are two kinds of Streams:

Input Stream: Used to read data from a source. This could be a file, array, peripheral device, or socket.
Output Stream: Used to write data to a destination. This could be a file, array, peripheral device, or socket.
The flow for an input stream is illustrated below:

Image description

Byte to Stream

Java byte stream are used to perform input and output of 8-bit bytes. Following is an example which makes use of these two classes to copy an input file into an output file −

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class LearnStream {
    public static void main(String[] args) throws IOException {

       var directory = "D://sample/stream/";
       var fileInput = new FileInputStream(directory+"input.txt");
       var fileOutput = new FileOutputStream(directory+"output.txt");

       try{
           int i;
           while((i= fileInput.read())!=-1){
               fileOutput.write(i);
           }
       } catch (IOException e) {
           throw new RuntimeException(e);
       }

    }

}

Copy after login

Now let's have a file input.txt with the following content

Dimas Priyandi
Software Developer
Java
Angular 
Spring Boot
Copy after login
Copy after login

Running program and we get a file with name output.txt with the following content

Dimas Priyandi
Software Developer
Java
Angular 
Spring Boot
Copy after login
Copy after login

Example

To better understand file input streams and file output streams, let's create a new sample where we have an input file named count.txt.

The contents of count.txt are as follows:

100
90
80
70
60
50
40
30
20
10
0
Copy after login

When the File Input Stream reads the numerical data from the file count.txt, we will store it in an array and then perform a summation operation to calculate the total sum of the data. Please follow the program code below:

import java.io.*;

public class LeanCount {
    public static void main(String[] args) throws FileNotFoundException {
        var directory = "D://sample/stream/";
        var fileInput = new FileInputStream(directory+"count.txt");
        var fileOutput = new FileOutputStream(directory+"sum.txt");
        Integer sum = 0;
        try{
            var reader = new BufferedReader(new InputStreamReader(fileInput));
            var outputWriter = new BufferedWriter(new OutputStreamWriter(fileOutput));
            String line;
            while((line=reader.readLine()) !=null){
                sum+=Integer.parseInt(line);
            }
            reader.close();
            outputWriter.write(sum.toString());
            outputWriter.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    }



Copy after login

Output:

  • we can see output of sum.txt is :
550
Copy after login

Explanation:

  • FileInputStream: Used to read bytes from the file count.txt.
  • InputStreamReader: Converts the bytes read by FileInputStream into characters.
  • BufferedReader: Provides the readLine() method to read the file line by line.
  • Numbers Array: An integer array to store the numbers read from the file.
  • Sum Calculation: A loop to sum up all the numbers stored in the array.
  • FileOutputStream: Used to write bytes to the file.
  • OutputStreamWriter: Converts the character stream to a byte stream.
  • BufferedWriter: Provides buffering for writing characters, arrays, and lines efficiently.

Summary

Java's I/O streams provide a powerful way to handle file operations. By using InputStream and OutputStream, and their buffered counterparts, you can efficiently read from and write to files.

The above is the detailed content of Tips for Using Java Streams for File Input/Output. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!