Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 7344

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T02:55:07+00:00 2024-11-28T02:55:07+00:00

Tips for Using Java Streams for File Input/Output

  • 60k

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);        }      }  }  
Enter fullscreen mode Exit fullscreen mode

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

Dimas Priyandi Software Developer Java Angular  Spring Boot 
Enter fullscreen mode Exit fullscreen mode

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

Dimas Priyandi Software Developer Java Angular  Spring Boot 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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);         }      }      }    
Enter fullscreen mode Exit fullscreen mode

Output:

  • we can see output of sum.txt is :
550 
Enter fullscreen mode Exit fullscreen mode

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.

javaoopprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.