JavaRush /Java Blog /Random EN /What is the PrintStream class for?

What is the PrintStream class for?

Published in the Random EN group
Hello! Today we'll talk about the class PrintStreamand everything it can do. What is the PrintStream class for? - 1Actually, you are already familiar with two methods of the class PrintStream. print()These are the and methods println()that you probably use every day :) Since a variable System.outis an object PrintStream, when you call a method System.out.println(), you are calling a method of this particular class. The general purpose of the class PrintStreamis to output information to some stream. This class has several constructors. Here are a few of the most common:
  • PrintStream(OutputStream outputStream)
  • PrintStream(File outputFile) throws FileNotFoundException
  • PrintStream(String outputFileName) throws FileNotFoundException
As you can see, we can pass into the constructor of the object PrintStream, for example, the name of the file into which we want to output the data. Or, alternatively, the object itself File. Let's look at how this works with examples:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class Main {

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

       filePrintStream.println(222);
       filePrintStream.println("Hello world");
       filePrintStream.println(false);
   }
}
This code will create a file on the desktop test.txt(if it does not already exist there) and write our number, string and boolean-variable there sequentially. Here are the contents of our file after the program runs:

222
Hello world!
false
As we said above, it is not necessary to pass the file object itself File. You just need to specify the path to it in the constructor:
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class Main {

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

       filePrintStream.println(222);
       filePrintStream.println("Hello world");
       filePrintStream.println(false);
   }
}
This code will do the same as the previous one. Another interesting method to look at is , printf()or formatted string output. What does "formatted string" mean? To explain, I'll give an example:
import java.io.IOException;
import java.io.PrintStream;

public class Main {

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

       PrintStream printStream = new PrintStream("C:\\Users\\Евгений\\Desktop\\test.txt");

       printStream.println("Hello!");
       printStream.println("I'm robot!");

       printStream.printf("My name is %s, my age is %d!", "Amigo", 18);

       printStream.close();

   }
}
Here, instead of explicitly writing down the name and age of our robot in a line, we seem to leave “free space” for this information using pointers %sand %d. And we pass the data that should be in these places as parameters. In our case, this is the string " Amigo " and the number 18. We could, for example, create another space: say, %b, and pass another parameter. What is it for? First of all, to increase flexibility. If your program needs to frequently display a welcome message, you will have to manually enter the required text for each new robot. You won’t even be able to put this text into a constant: everyone’s names and ages are different! But using the new method, you can output a string with a greeting to a constant, and if necessary, simply change the parameters in the method printf().
import java.io.IOException;
import java.io.PrintStream;

public class Main {

   private static final String GREETINGS_MESSAGE = "My name is %s, my age is %d!";

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

       PrintStream printStream = new PrintStream("C:\\Users\\Евгений\\Desktop\\test.txt");

       printStream.println("Hello!");
       printStream.println("We are robots!");

       printStream.printf(GREETINGS_MESSAGE, "Amigo", 18);
       printStream.printf(GREETINGS_MESSAGE, "R2-D2", 35);
       printStream.printf(GREETINGS_MESSAGE, "C-3PO", 35);

       printStream.close();
   }
}

System.in spoofing

In this lecture we will “fight the system” and learn how to replace a variable System.inand redirect the system output to the place we need. What is the PrintStream class for? - 2You might have forgotten what it is System.in, but no JavaRush student will ever forget this construction:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.in(like System.out) is a static class variable System. But, unlike System.out, it belongs to a different class, namely, to InputStream. By default System.in, this is a thread that reads data from the system device—the keyboard. However, as in the case with System.out, we can replace the data source, and reading will not occur from the keyboard, but from the location we need! Let's look at an example:
import java.io.*;

public class Main {

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

       String greetings = "Hello! Меня зовут Амиго!\nЯ изучаю Java на сайте JavaRush.\nОднажды я стану крутым программистом!\n";
       byte[] bytes = greetings.getBytes();

       InputStream inputStream = new ByteArrayInputStream(bytes);

       System.setIn(inputStream);

       BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

       String str;

       while ((str = reader.readLine())!= null) {

           System.out.println(str);
       }

   }
}
So what did we do? Usually System.in“tied” to the keyboard. But we don’t want the data to be read from the keyboard: let it be read from a regular line of text! We created a string and received it as a byte array. Why do we need bytes? The fact is that it InputStreamis an abstract class, and we cannot create an instance of it. You will have to choose some class from among its heirs. For example, we can take ByteArrayInputStream. It is simple, and just by its name it is clear how it works: its data source is a byte array. So we create this same byte array and pass it to our constructor stream, which will read the data. In fact, everything is already ready! Now we just need to use the method System.setIn()to explicitly set the value of the variable in. In the case of out, as you remember, it was clearly impossible to set the value of the variable either: you had to use a special method setOut(). After we have assigned InputStreamthe variable we created System.in, we need to check whether our idea worked. An old friend will help us with this - BufferedReader. In a normal situation, this code would cause a console to open in your Intellij IDEa, and the data you entered from the keyboard would be read from there.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

       String str;

       while ((str = reader.readLine())!= null) {

           System.out.println(str);
       }
But when you run it now, you will see that our text from the program will simply be output to the console, there will be no reading from the keyboard. We have changed the data source, now it is not the keyboard, but our string! It's so easy and simple :) In today's lecture we got acquainted with a new class and looked at a new small “hack” for working with I/O. Time to get back to the course and solve some problems :) See you in the next lecture!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION