• Register

Java’s IO approach is one of its special abilities that makes it distinguished from other languages.

To start, the use of IO in Java presents many advantages from which we can mention:

 – The permanent save of data in an independent file.

 – The pipeline between programs (The output of one could be the input to another).

 – The automated input into a program (Could read all the data from input file by a loop).

When it comes to manipulating the IO, 3 main actions are required:

First, to open the stream by connecting to an external file.

Second, you execute the read and write operations via the stream.

And finally, you close it.

Now talking about the stream, it’s diverged into 2 different roles: Input Stream and Output Stream.

And each one could either be Buffered ( big lines approach ), or not buffered ( Byte by Byte approach ).

We’ll now be implementing the most popular IO classes in java in the following snippet.

N.B: All the IO operations could trigger an IOException, which is why all our manipulations will be surrounded by a try and catch block.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test {

	public static void main(String[] args) {

		try {
			File source = new File ("input.txt");       //Refers to the file that has the data to be read

			FileReader f = new FileReader(source);

			BufferedReader b = new BufferedReader(f);  //Buffered to read big lines

			File dest = new File("output.txt");  //Refers to the file that we will be writing the data on

			FileWriter fw =  new FileWriter(dest);

			BufferedWriter w = new BufferedWriter(fw);

			String line;

			while((line=b.readLine())!=null) {  //Each time we found a line in the input, we'll enter in the loop and write it in the output file

				w.write(line);
				w.write("\n");

			}

			b.close();  //Close the input stream
			w.close();  //Close the output stream

		} catch (FileNotFoundException e) {
			
			e.printStackTrace();

		} catch (IOException e) {
			
			e.printStackTrace();
		}

	}

}

 

100 points
3