JavaRush /Java Blog /Random EN /Practice working with the BufferedReader and InputStreamR...

Practice working with the BufferedReader and InputStreamReader classes

Published in the Random EN group
Hello! Today's lecture will be divided into two parts. We will repeat some of the old topics that we have already touched on before, and look at some new features :) Practice working 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 needed for. Happened? If not, don’t worry :) If by this point you have forgotten something, re-read this lecture dedicated to readers again. Let's briefly remember what each of them can do. System.inis a thread for receiving data from the keyboard. In principle, to implement the logic of reading the text, one 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 run 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 that are 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 this time will be different:

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

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

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

Й
Well, as for BufferedReader'a (and in general - BufferedAnything), buffered classes are used to optimize performance. Accessing a data source (file, console, resource on the Internet) 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 later receive it. As a result, the number of calls to the data source is reduced by several times or even tens of times! Another additional feature of BufferedReader'a and its advantage over regular InputStreamReader' is the extremely useful method readLine()that reads data as whole strings rather than as individual numbers. This, of course, greatly adds convenience when implementing, for example, large text. This is what reading a line would 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 working with the BuffreredReader and InputStreamReader classes - 2Of course, BufferedReaderit is a very flexible mechanism and allows you to work not only with the keyboard. You can read data, for example, directly from the Internet by simply passing the required 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();
   }
}

Substitution of System.out

Now let's look at one interesting possibility that we haven't touched on before. As you probably remember, Systemthere are two static fields in the class - System.inand System.out. These twin brothers are thread class objects. System.in- abstract class InputStream. A System.out- class PrintStream. Now we will talk specifically 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.outjust a regular static class variableSystem . There is no magic in it :) The variable outbelongs to the class PrintStream. Here's an interesting question: why, when executing code, System.out.println()does the output appear in the console and not somewhere else? And is it possible to change this 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 reader and writer classes, but simply using System.out? Still as possible :) And although the variable System.outis designated by a modifier final, we can still do it! Practice working with the BuffreredReader and InputStreamReader classes - 3So what do we need for this? Firstly , we need a new class object PrintStreaminstead of the current one. The current object installed in the class Systemby 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. Secondly , you need to understand how to assign a new value to a variable System.out. You can’t just do it like that, because it’s marked final. Let's start from the end. The class Systemcontains exactly the method we need - setOut(). It takes an object as input PrintStreamand sets it as the output point. Just what we need! All that remains is to create the object PrintStream. This is also easy to do:
PrintStream filePrintStream = new PrintStream(new File("C:\\Users\\Username\\Desktop\\test.txt"));
The entire 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 will be output to the console :) You can copy this code to your IDE and run it. By opening the text file, you will see that the required line has been successfully written there :) This concludes the lecture. Today we remembered how to work with streams and readers, recalled how they differ from each other and learned about new features System.outthat we used in almost every lesson :) See you in the next lectures!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION