Java writer class is an abstract class in the java.io package. It is designed for writing character streams. Writer class in Java provides methods for writing characters, arrays of characters, and strings. Since it is an abstract class, we cannot create an instance of it directly. Instead, we will use one of its concrete subclasses such as FileWriter, BufferedWriter, or PrintWriter.
Example 1: The below Java program demonstrates the working of the FileWriter class to write data to a text file.
Java
// Demonstrate the woking of FileWriter class
import java.io.FileWriter;
import java.io.IOException;
public class Geeks {
public static void main(String[] args)
{
try {
// Create a FileWriter to write to a file named
// "example.txt"
FileWriter w = new FileWriter("example.txt");
// Write a simple message to the file
w.write("Hello, World!");
// Close the writer
w.close();
System.out.println(
"Geeks for Geeks");
}
catch (IOException e) {
System.out.println("An error occurred: "
+ e.getMessage());
}
}
}
Declaration of the Writer Class
public abstract class Writer extends Object implements Appendable, Closeable, Flushable
Constructors of the Writer Class
The Writer
class in Java has two protected constructors that allow for the creation of character streams with synchronization capabilities.
- Protected
Writer():
Creates a new character stream that can itself synchronize on the writer. - protected Writer(Object obj): Creates a new character stream that can itself synchronize on the given object – ‘obj’.
Java Writer Class Methods
There are certain methods associated with the Java Writer class as mentioned below:
1. write(int char)
- Itwrites a single character to the character stream.
- Characters being written are contained in 16 lower bits of the 'char' integer value, the rest of the 16 higher bits are ignored by the method.
Syntax:
public void write(int char)
- Parameter: Theinteger value of the character to be written.
- Return type: This method does not return any value
- Exception: Throws IOException if an I/O error occurs during writing.
2. write(String str)
It writes a string to the character stream.
Syntax:
public void write(String str)
- Parameter: string to be written to the character stream.
- Return type: This method does not return any value
- Exception: Throws IOException if an I/O error occurs during writing.
3. write(String str, int offset, int maxlen)
It writes some part of the string to the character stream.
Syntax:
public void write(String str, int offset, int maxlen)
- Parameter:
- str: string to be written to the character stream.
- offset: start position of the String
- maxlen: maximum length upto which string has to written
- Return type: This method does not return any value
- Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O error occurs.
4. write(char[] carray)
It writes character array to the character stream.
Syntax:
public void write(char[] carray)
- Parameter: Thecharacter array to be written to the character stream
- Return type: This method does not return any value
- Exception: Throws IOException if an I/O error occurs during writing.
5. write(char[] carray, int offset, int maxlen)
It writes some part of the character array to the character stream.
Syntax:
public abstract void write(char[] carray, int offset, int maxlen)
- Parameter:
- carray: character to be written to the character stream
- offset: start position of the character array
- maxlen: maximum no. of the character of the carray has to written
- Return type: This method does not return any value
- Exception: Throws IndexOutOfBoundsException if the offset or maxlen is invalid, and IOException if an I/O error occurs.
6. close()
It closes the character stream, flushing it first.
Syntax:
public abstract void close()
- Parameter: This method does not take any parameter.
- Return type: This method does not return any value.
- Exception: Throws IOException if an I/O error occurs during closing.
7. flush()
It flushes the Writer stream. Flushing one stream invocation will flush all other buffer in chain.
Syntax:
public void flush()
- Parameter: This method does not take any parameter.
- Return type: This method does not return any value.
- Exception: Throws IOException if an I/O error occurs while flushing.
8. append(char Sw)
It appends a single character to the Writer.
Syntax:
public Writer append(char Sw)
- Parameter: character to be append
- Return type: This method return a writer.
- Exception: Throws IOException if an I/O error occurs during appending.
9. append(CharSequence char_sq)
It appends specified character sequence to the Writer.
Syntax:
public Writer append(CharSequence char_sq)
- Parameter: Character sequence to append.
- Return type: This method return a writer, if char sequence is null, then NULL appends to the Writer.
- Exception: Throws NullPointerException if the char_sq is null and IOException if an I/O error occurs during appending.
10. append(CharSequence char_sq, int start, int end)
It appends specified part of a character sequence to the Writer.
Syntax:
public Writer append(CharSequence char_sq, int start, int end)
- Parameter:
- char_sq: Character sequence to append.
- start: start of character in the Char Sequence
- end: end of character in the Char Sequence
- Return type: This method does not return value.
- Exception: Throws IndexOutOfBoundsException if the start or end values are invalid, and IOException if an I/O error occurs.
Example 2: The below Java program demonstrates how to append individual character, entire sequence and substrings to the writer.
Java
// Java Program to demonstrates appending
// Characters and String to the writer
import java.io.*;
public class Main {
public static void main(String[] args)
throws IOException
{
// Writer to output to the console
Writer w = new PrintWriter(System.out);
System.out.println("Example 1: append(char)");
// Appending Characters
w.append('G');
w.append('e');
w.append('e');
w.append('k');
w.append('s');
w.flush();
System.out.println();
System.out.println(
"Example 2: append(CharSequence)");
CharSequence t = "Hello, Geeks!";
// Appending entire CharSequence
w.append(t);
w.flush();
System.out.println();
System.out.println(
"Example 3: append(CharSequence, start, end)");
// Appending substring "Hello"
w.append(t, 0, 5);
w.append(" ");
// Appending substring "Geeks"
w.append(t, 7, 12);
w.flush();
System.out.println();
// Close the writer
w.close();
}
}
OutputExample 1: append(char)
Geeks
Example 2: append(CharSequence)
Hello, Geeks!
Example 3: append(CharSequence, start, end)
Hello Geeks
Similar Reads
Java Reader Class Reader class in Java is an abstract class used for reading character streams. It serves as the base class for various subclasses like FileReader, BufferedReader, CharArrayReader, and others, which provide more efficient implementations of the read() method. To work with the Reader class, we must ext
6 min read
Wrapper Classes in Java A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
6 min read
Nested Classes in Java In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
5 min read
Object Class in Java Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
7 min read
Static class in Java Java allows a class to be defined within another class. These are called Nested Classes. Classes can be static which most developers are aware of, henceforth some classes can be made static in Java. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes. The class
3 min read