Course Content
Core Java
About Lesson

PrintStream

PrintStream is a class in the java.io package, which is used for outputting data. It extends OutputStream class. It provides various methods to print representations of data values conveniently. All characters printed by a PrintStream are converted into bytes using the platform’s default character encoding.

Unlike other output streams, PrintStream never throws an IOException. Instead, it has a method to check for errors, and if an error occurs, it sets an internal flag that can be queried.

The PrintStream class automatically flushes the data so there is no need to call the flush() method. The flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

Constructors

  1. PrintStream(File file): Creates a new print stream, without automatic line flushing, with the specified file
  2. PrintStream(File file, String csn): Creates a new print stream, without automatic line flushing, with the specified file and charset.
  3. PrintStream(OutputStream out): Creates a new print stream that outputs to the mentioned OutputStream. This stream will not flush automatically.
  4. PrintStream(OutputStream out, boolean autoFlush): Creates a new print stream that outputs to the mentioned OutputStream. If autoFlush is true, the output buffer will be flushed automatically.
  5. PrintStream(OutputStream out, boolean autoFlush, String encoding): Creates a new print stream that outputs to the mentioned OutputStream. If autoFlush is true, the output buffer will be flushed automatically. The characters will be encoded using the given charset.
  6. PrintStream(String fileName): Creates a new print stream, without automatic line flushing, with the specified file name. Characters would be encoded using default charset of JVM.
  7. PrintStream(String fileName, String csn): Creates a new print stream, without automatic line flushing, with the specified file name. Characters would be encoded using the provided charset.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintStreamExample {

    public static void main(String[] args) {
        try {
            // Create a new PrintStream object using FileOutputStream
            PrintStream ps = new PrintStream(new FileOutputStream("example.txt"));

            // Demonstrate different print methods
            ps.print("This is a string");
            ps.print(123); // Print an integer
            ps.print('A'); // Print a character
            ps.print(45.67); // Print a double
            ps.print(true); // Print a boolean

            // Demonstrate different println methods
            ps.println();
            ps.println("This is another string with println");
            ps.println(456); // Print an integer with a newline
            ps.println('B'); // Print a character with a newline
            ps.println(89.01); // Print a double with a newline
            ps.println(false); // Print a boolean with a newline

            // Using format method
            ps.format("Formatted string: %d %s %f%n", 789, "example", 12.34);

            // Using printf method (equivalent to format)
            ps.printf("Formatted using printf: %d %s %f%n", 789, "example", 12.34);

            // Demonstrating the use of append method
            ps.append("Appending a string");
            ps.append('C');
            ps.append(" and more text");

            // Always close the stream
            ps.close();

            // Reading the file to show the output (optional)
            System.out.println("Data written to 'example.txt':");
            java.nio.file.Files.lines(java.nio.file.Paths.get("example.txt")).forEach(System.out::println);

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

Common Methods

print(Object obj): These methods print various data types to the output stream without a newline character.

print(int i): Prints an integer without a newline character. The string produced by String.valueOf(int) is translated into bytes.

println: Prints the object with a newline character.

printf(String format, Object… args): write a formatted string to this output stream using the specified format string and arguments. Format string is described in (https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax)

format(String format, Object… args): Writes a formatted string to this output stream using the specified format string and arguments.

append(CharacterSequence csq): Appends the specified character sequence to the given output stream.

Code to get default and available charset

import java.nio.charset.Charset;

public class DefaultCharsetExample {
    public static void main(String[] args) {
        // Get the default charset
        Charset defaultCharset = Charset.defaultCharset();

        // Print the default charset
        System.out.println("Default Charset: " + defaultCharset);

        // Get the name of the default charset
        String charsetName = defaultCharset.name();
        System.out.println("Default Charset Name: " + charsetName);

        // List all available charsets
        System.out.println("Available Charsets:");
        for (String charset : Charset.availableCharsets().keySet()) {
            System.out.println(charset);
        }
    }
}

Unicode

The char data type are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. It is a comprehensive character encoding standard designed to support all characters used in human languages around the world. Unicode assigns a unique code point to every character, which is a number written in hexadecimal format, such as U+0041 for ‘A’.

Character Set

A character set (also known as a charset) is a collection of characters that a computer system recognizes and can represent. It defines the relationship between the characters (letters, digits, symbols) and their binary representations.

Encoding Schemes

Encoding schemes are methods to convert Unicode code points into sequences of bytes. The most commonly used encoding schemes are UTF-8, UTF-16, and UTF-32.

PrintWriter

PrintWriter is a character-oriented class for writing text-based data. It extends Writer and provides convenient methods for writing various data types and for printing formatted text.

This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes.

Methods in this class never throw I/O exceptions, although some of its constructors may.

If automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.

Constructors

  1. PrintWriter(Writer out): Creates a new PrintWriter outputting to the given character output stream, without automatic line flushing.
  2. PrintWriter(Writer out, boolean autoFlush): Creates a new PrintWriter to the given character output stream. For automatic flushing, set autoFlush to true.
  3. PrintWriter(OutputStream out): Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. This creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.
  4. PrintWriter(OutputStream out, boolean autoFlush): Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. For automatic flushing, set autoFlush to true.
  5. PrintWriter(String fileName): Creates a new PrintWriter, without automatic line flushing, with the specified file name.
  6. PrintWriter(String fileName, String csn): Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
  7. PrintWriter(File file): Creates a new PrintWriter, without automatic line flushing, with the specified file.
  8. PrintWriter(File file, String csn): Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
import java.io.*;

public class PrintWriterMethodsExample {

    public static void main(String[] args) {
        String fileName = "output.txt";

        try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
            // Writing various data types
            pw.println("Hello, PrintWriter!");
            
            int num = 123;
            String str = "example";
            double value = 45.67;
            
            // Using printf for formatted output
            pw.printf("Formatted Number: %d, String: %s%n", num, str);
            
            // Using print method
            pw.print("This is a line.");
            
            // Using println method to write a new line
            pw.println(" This is another line.");
            
            // Writing numbers using print and println
            pw.print("Number: ");
            pw.println(456);
            
            // Using format for formatted output
            pw.format("Formatted Value: %.2f%n", value);
            
            // Using println to write a boolean value
            boolean flag = true;
            pw.println("Flag: " + flag);
            
            // Flushing the PrintWriter
            pw.flush();
            
            System.out.println("Data written to " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Common Methods

flush(): Forces any buffered output bytes to be written out to the underlying output stream.

append(CharSequence csq) : Appends the specified character sequence to this writer.

format(String format, Object… args): Writes a formatted string to this writer using the specified format string and arguments.

write(char[] buf): Write an array of characters.

Scroll to Top