JavaRush /Java Blog /Random EN /Practice with the BuffreredReader and InputStreamReader c...

Practice with the BuffreredReader and InputStreamReader classes

Published in the Random EN group
Hello! Today's lecture will be divided into two conditional parts. We'll revisit some of the old topics we've touched on before and look at some of the new features :) Practice with the BuffreredReader and InputStreamReader classes - 1Let's start with the first one. Repetition is the mother of learning :) You have already used such a class as BufferedReader. I hope you haven't forgotten this command yet:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Before reading further, try to remember what each component ( System.in, InputStreamReader, BufferedReader) is responsible for and what they are for. Happened? If not, don't worry :) If by this point you forgot about something, re-read this lecture on readers again. Briefly recall what each of them can do. System.inis a thread for receiving data from the keyboard. In principle, in order to implement the logic of reading the text, one of them would be enough for us. But, as you remember, System.init can only read bytes, not characters:
public class Main {

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

       while (true) {
           int x = System.in.read();
           System.out.println(x);
       }
   }
}
If we execute this code and enter the letter "Y" in the console, the output will be like this:

Й
208
153
10
Cyrillic characters occupy 2 bytes in memory, which are displayed on the screen (and the number 10 is the byte representation of a line break, i.e. pressing Enter). Reading bytes is such a pleasure, so using it System.inin its pure form will be inconvenient. In order to read Cyrillic (and not only) letters understandable to everyone, we use InputStreamReaderas a wrapper:
public class Main {

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

       InputStreamReader reader = new InputStreamReader(System.in);
       while (true) {
           int x = reader.read();
           System.out.println(x);
       }
   }
}
If we enter the same letter "Y" into the console, the result will be different this time:

Й
1049
10
InputStreamReaderconverted the two bytes read (208, 153) to a single number 1049. This is the read character by character. 1049 corresponds to the letter "Y", which can be easily seen:
public class Main {

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

       char x = 1049;
       System.out.println(x);
   }
}
Console output:

Й
As for BufferedReader'a (and BufferedAnything in general), buffered classes are used to optimize performance. Accessing a data source (file, console, network resource) is a rather expensive operation in terms of performance. Therefore, in order to reduce the number of such calls, BufferedReaderit reads and accumulates data in a special buffer, from where we can then receive them. As a result, the number of calls to the data source is reduced by several times or even dozens of times! Another additional feature of BufferedReader'a and its advantage over the usual InputStreamReader'th is an extremely useful methodreadLine(), which reads data as whole lines rather than individual numbers. This, of course, greatly adds convenience when implementing, for example, a large text. Here's what the line will look like:
public class Main {

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

       BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
       String s = reader.readLine();
       System.out.println("Пользователь ввел следующий текст:");
       System.out.println(s);
       reader.close();
   }
}

BufferedReader+InputStreamReader работает быстрее, чем просто InputStreamReader
Пользователь ввел следующий текст:
BufferedReader+InputStreamReader работает быстрее, чем просто InputStreamReader
Practice with the BuffreredReader and InputStreamReader classes - 2Of course BufferedReader- a very flexible mechanism, and allows you to work not only with the keyboard. You can read data, for example, directly from the Web by simply passing the desired URL to the reader:
public class URLReader {
   public static void main(String[] args) throws Exception {

       URL oracle = new URL("https://www.oracle.com/index.html");
       BufferedReader in = new BufferedReader(
               new InputStreamReader(oracle.openStream()));

       String inputLine;
       while ((inputLine = in.readLine()) != null)
           System.out.println(inputLine);
       in.close();
   }
}
You can read data from a file by passing the path to it:
public class Main {
   public static void main(String[] args) throws Exception {

       FileInputStream fileInputStream = new FileInputStream("testFile.txt");
       BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));

       String str;

       while ((str = reader.readLine()) != null)   {
           System.out.println (str);
       }

       reader.close();
   }
}

Replacing System.out

Now let's look at one interesting possibility that we haven't touched on before. As you probably remember, the class Systemhas two static fields - System.inand System.out. These twin brothers are objects of stream classes. System.in- abstract class InputStream. A System.out- class PrintStream. Now we'll talk about System.out. If we go into the source code of the class System, we will see this:
public final class System {

……………...

public final static PrintStream out = null;

  …………

}
So, System.outit's just a regular static class variableSystem . There is no magic in it :) The variable outbelongs to the class PrintStream. Here is an interesting question: why, when executing the code, System.out.println()the output is made to the console, and not somewhere else? And can this be changed somehow? For example, we want to read data from the console and write it to a text file. Is it possible to somehow implement such logic without using additional classes of readers and writers, but simply using System.out? Even better :) And although the variable System.outis marked with the modifier final, we can still do it! Practice with the BuffreredReader and InputStreamReader classes - 3So what do we need for this? First , we need a new class object PrintStreamto replace the current one. The current object set in the classSystemby default, does not suit us: it points to the console. We need to create a new one that will point to a text file as the "destination" for our data. Second , you need to understand how to assign a new value to a variable System.out. Just do not do it, because it is marked final. Let's start from the end. The class Systemjust has the method we need - setOut(). It takes an object as input PrintStreamand sets it as the output point. Just what we need! It remains only to create an object PrintStream. This is also easy to do:
PrintStream filePrintStream = new PrintStream(new File("C:\\Users\\Username\\Desktop\\test.txt"));
The whole code will look like this:
public class SystemRedirectService {

   public static void main(String arr[]) throws FileNotFoundException
   {
       PrintStream filePrintStream = new PrintStream(new File("C:\\Users\\Username\\Desktop\\test.txt"));

       /*Сохраним текущее meaning System.out в отдельную переменную, чтобы потом
       можно было переключиться обратно на вывод в консоль*/
       PrintStream console = System.out;

       // Присваиваем System.out новое meaning
       System.setOut(filePrintStream);
       System.out.println("Эта строка будет записана в текстовый файл");

       // Возвращаем System.out старое meaning
       System.setOut(console);
       System.out.println("А эта строка - в консоль!");
   }
}
As a result, the first line will be written to a text file, and the second line will be output to the console :) You can copy this code to your IDE and run it. When you open a text file, you will see that the required string has been successfully written there :) This concludes the lecture. Today we remembered how to work with streams and readers, restored in memory how they differ from each other and learned about new features System.outthat we used in almost every lesson :) See you at the next lectures!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION