Work with the console in Java. Classes InputStreamReader, PrintStream. Creating an input/output stream associated with the console. Redirecting input/output streams to a file, from a file, from a string. Examples
Contents
- 1. Create an input stream associated with the console. Class InputStreamReader
- 2. Creating an output stream associated with the console. Class PrintStream. Methods print(), println(). Example
- 3. Class InpusStreamReader. Reading characters from the console using the read() method. Examples
- 4. Reading characters from a console with buffering. Classes InputStreamReader, BufferedStreamReader. Example
- 5. Writing data to the console. Output an array of real numbers to the console. Class PrintStream. Example
- 6. Reading lines from a console with buffering support and displaying them on the screen. Classes InputStreamReader, BufferedStreamReader. ReadLine() method. Example
- 7. Reading lines from the console and writing them to a file. Classes InputStreamReader, BufferedReader, FileInputStream, PrintStream. Example
- 8. Reading lines from a character file and outputting them to the console. Class FileReader. Example
- 9. Classes PrintStream, FileOutputStream. Redirecting the output stream from String to a file. Example
- Related topics
Search other websites:
1. Create an input stream associated with the console. Class InputStreamReader
The input stream from the console can be organized in one of two ways:
- using an input byte stream;
- using a character input stream. In this case, the data that is entered from the console is read from the standard input stream, which corresponds to the variable System.in from the java.lang package. In other words, the System.in variable refers to the standard input stream, which, by default, is the keyboard.
In the Java language, the InputStreamReader class is used to implement console input operations. This class is a subclass of the abstract base class Reader and is designed to convert bytes to characters.
To get an object of type InputStreamReader you need to create an instance of this type in the following general form
InputStreamReader objStream = new InputStreamReader(input_stream);
here
- objStream – an instance that is associated with a character input stream;
- inputStream – character input stream. In the case of the console, this stream is the variable System.in.
So, for the System.in stream, to create an instance (object) of type InputStreamReader, you need to call the following constructor
InputStreamReader objStream = new InputStreamReader(System.in);
⇑
2. Creating an output stream associated with the console. Class PrintStream. Methods print(), println(). Example
The java.lang package implements two variables that are associated with the stream of writing data to the console:
- System.out. This variable corresponds to the console output stream;
- System.err. This variable is associated with the error output stream.
To work with console output, a special PrintStream class has been developed, which is derived from the OutputStream class. The main methods in this class are print() and println().
To create an output stream associated with the console, you must declare an instance of the PrintStream class. When creating an instance, you need to associate it with the corresponding stream as shown in the following example
import java.io.*; ... public static void main(String[] args) throws IOException { // Creating an output stream. Class PrintStream. // 1. Link the outStream reference with the System.out stream PrintStream outStream = new PrintStream(System.out); // 2. Link the errStream reference with the System.err stream PrintStream errStream = new PrintStream(System.err); // 3. Use both references outStream.println("Hello world!"); // Method println() errStream.print("Some error..."); // Method print() }
The result of the program
Hello world! Some error...
⇑
3. Class InpusStreamReader. Reading characters from the console using the read() method. Examples
As you know, the standard variable System.in is associated with the console. To read characters from the console without buffering, you can use the capabilities of the InputStreamReader class. The InputStreamReader class is a subclass of the abstract class Reader. The InputStreamReader class is designed to convert bytes to characters.
The main method of the InputStreamReader class is the read() method, which has two overloaded implementations. The first implementation has the following general form
int read();
In this case, the method returns the code of the entered character from the console.
The general form of the second implementation of the method is as follows
int read(char[] ac, int index, int count);
Here, the method fills an ac array of type char[] with the entered character values from the console. The count parameter specifies the number of characters to insert into the ac array. For ac array, memory can be preliminarily allocated. The second variant of the method returns the number of characters that can be read.
Example 1. To read a single character from an input stream (console), use the read() method. The following is the ReadConsolle() function, which demonstrates reading characters from the console without buffering. Characters are read until the ‘ . ‘ character is entered.
import java.io.*; ... // Example of reading characters from the System.in console // without using buffering. public void ReadConsolle() throws IOException { char c; // Create a stream instance that is associated with the console InputStreamReader sr = new InputStreamReader(System.in); System.out.println("Enter characters, '.' - to exit."); // character read loop do { c = (char)sr.read(); System.out.println(c); } while (c != '.'); }
Example 2. Using the read() method, which processes an array of type char[].
import java.io.*; ... // Using a variant of the read() method that fills an array // of characters of type char[] with characters entered from the console. // General form of the method: // int read(char[], int, int) public void ReadConsolle2() throws IOException { // 1. Declare internal variables char arrChar[] = new char[10]; // array of type char[] - memory buffer InputStreamReader sr = new InputStreamReader(System.in); // input stream that is associated with the console int count; // Number of characters read // Read 4 characters from the console. // Write these characters to the arrChar array starting at position 0. System.out.println("Enter characters (maximum 10):"); count = sr.read(arrChar, 0, 4); // Display the result System.out.println("You can process " + count + " characters"); System.out.println("The arrChar after input:"); for (int i=0; i<arrChar.length; i++) System.out.println("arrC[" + i + "] = " + arrChar[i]); }
The result of the program
Enter characters (maximum 10): sds You can process 4 characters The arrChar after input: arrC[0] = s arrC[1] = d arrC[2] = s arrC[3] = arrC[4] =
⇑
4. Reading characters from a console with buffering. Classes InputStreamReader, BufferedStreamReader. Example
To implement buffering when reading characters from the console, you need to put an instance of the InputStreamReader class into the shell of the BufferedReader class object. In this case, the general form of the constructor for the BufferedReader class is as follows
BufferedReader(Reader input_stream)
here
- input_stream – some data stream (file, console, etc.). In the case of the console, an instance of the InputStreamReader class is specified here (see the previous paragraph).
This approach implements the Decorator pattern. In the Decorator pattern, an instance of one class serves as a wrapper for an instance of another class. Thus, layering of objects occurs.
The following is an example of the ReadConsoleBuf() function, which implements reading characters from a console with buffering.
import java.io.*; ... // Reading characters from the console with support for buffering public void ReadConsolleBuf() throws IOException { char c; // Create a stream instance that is associated with the console InputStreamReader sr = new InputStreamReader(System.in); // Declare an instance of the BufferedReader class, // place an instance of the InputStreamReader stream in it BufferedReader br = new BufferedReader(sr); System.out.println("Input characters, '.' - to exit."); // character read loop do { c = (char)br.read(); System.out.println(c); } while (c != '.'); }
⇑
5. Writing data to the console. Output an array of real numbers to the console. Class PrintStream. Example
An example is a demo. The output occurs in an instance of the PrintStream class, which is associated with the console (System.out variable).
import java.io.*; ... public static void main(String[] args) throws IOException { // Outputting an array of real numbers to the console // 1. Create the input data - an array of real numbers. Fill array with values double AD[] = new double[5]; for (int i=0; i<AD.length; i++) AD[i] = i*2.5 + 1; // 2. Create an instance of PrintStream class PrintStream ps = new PrintStream(System.out); // 3. Display the array using println() method ps.println("Array AD:"); for (int i=0; i<AD.length; i++) ps.println(AD[i]); }
⇑
6. Reading lines from a console with buffering support and displaying them on the screen. Classes InputStreamReader, BufferedStreamReader. ReadLine() method. Example
You can read lines from the console using buffering or without buffering. If the buffering mechanism is used, then the InputStreamReader class is placed in the constructor of the BufferedReader class.
Reading one line is carried out via readLine() function.
import java.io.*; ... public static void main(String[] args) throws IOException { // Read lines from a buffered console. Display lines // Use the readLine() method InputStreamReader sr = new InputStreamReader(System.in); // create an instance InputStreamReader BufferedReader br = new BufferedReader(sr); // buffering class instance String s; System.out.println("Enter strings:"); do { s = br.readLine(); // read one line System.out.println(s); // display this line on the screen } while (!s.equals("end")); // until the string "end" is entered }
The result of the program:
Enter strings: abc abc def def 0 1 2 0 1 2 end end
⇑
7. Reading lines from the console and writing them to a file. Classes InputStreamReader, BufferedReader, FileInputStream, PrintStream. Example
The example demonstrates redirecting input from the console to a text file.
import java.io.*; ... public static void main(String[] args) throws IOException { // Read lines from the console and write them to a file. // Use method readLine() // 1. Declaring class instances that receive data (rows) InputStreamReader sr = new InputStreamReader(System.in); // create an instance InputStreamReader BufferedReader br = new BufferedReader(sr); // buffering class // 2. Declaring class instances that display lines FileOutputStream fos = new FileOutputStream("strings.txt"); PrintStream ps = new PrintStream(fos); // 3. Additional variable String s; // 4. The cycle for entering lines from the console and writing them to a file System.out.println("Enter strings:"); do { s = br.readLine(); // read one line System.out.println(s); // display this line on the screen ps.println(s); // write this line to the stream ps => write to the file "strings.txt" } while (!s.equals("end")); // until the string "end" is entered ps.close(); }
The result of the program:
Enter strings: abc abc def def 0 1 2 3 0 1 2 3 end end
The content of file “strings.txt”
abc def 0 1 2 3 end
⇑
8. Reading lines from a character file and outputting them to the console. Class FileReader. Example
Let a character (text) file be set, which must be displayed on the console. Reading lines from a file can be implemented using the read() method of the FileReader class. A line from a file is read into a previously allocated memory location – a buffer.
To determine the end of a file, you need to use the ready() method of the FileReader class. If the end of the file, then the method returns false.
import java.io.*; ... public static void main(String[] args) throws IOException { // Read lines from a file and print them to the console FileReader fr = new FileReader("strings.txt"); char buffer[] = new char[1000]; // buffer for reading lines // The cycle of reading lines from a file do { fr.read(buffer); // Read string to the buffer System.out.println(buffer); // Print string to console } while (fr.ready()); // checking if the end of the file fr.close(); }
⇑
9. Classes PrintStream, FileOutputStream. Redirecting the output stream from String to a file. Example
Let some string of type String be given. It is necessary to write this line to the file by using the redirection of the output stream to the file. To implement writing a line to a file, you must perform the following steps:
- create an instance of the FileOutputStream class with the name of the file to which the line will be written;
- create an instance of the PrintStream class, in whose constructor place the created instance of the FileOutputStream class;
- use one of the print() or println() methods to write a string to a file.
A fragment of program code that redirects the output stream from a line to a file, the following
import java.io.*; ... public static void main(String[] args) throws IOException { // Redirect the output from a String to a file called "output.txt" // 1. Input data String s = "www.bestprog.net"; // string that is written to the file String filename = "output.txt"; // name of the file to which the string is written // 2. Create an instance of FileOutputStream class FileOutputStream fs = new FileOutputStream(filename); // 3. Create an instance of PrintStream class, in which place the instance FileOutputStream PrintStream ps = new PrintStream(fs); // 4. Write the line "www.bestprog.net" to the file "output.txt" ps.println(s); // 5. Close the file ps.close(); }
In this example, you can implement a function that writes an array of strings to a file.
⇑
Related topics
- Java I/O system. Streams. Byte streams. Character streams. Standard streams
- Work with files in Java. Class File. Basic working methods
⇑