×

Java file Writer

File Writer:

It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant of writing a set of characters. It creates an output file.

Writer Class:

It is a class of Java.io package, it represents the set of characters. It is an abstract class.

Writer Subclasses:

  • Buffered Writer
  • File Writer
  • String Writer
  • Output Stream Writer

Writer class object creation Syntax:

Writer object1 = new FileWriter();

Note: Here, to create an object we use FileWriter because the Writer class is abstract.

Constructors in File Writer:

  • FileWriter (File f)
  • FileWriter (File f, boolean ap)
  • FileWriter (FileDescriptor fdes)
  • FileWriter (String fN)
  • FileWriter (String fN, Boolean ap)
  • FileWriter (File f, Charset chset)
  • FileWriter (File f, Charset chset, boolean ap)
  • FileWriter (String fN, Charset chset, boolean ap)

FileWriter (File f):It creates or generates a file Writer object. It throws n IOException i.e, Input or Output Exception.

Syntax for creating object:

FileWriter f = new FileWriter(File f);

FileWriter (File f, boolean ap): It creates or generates a file writer object. If the given second argument is true then, it will be written the end of the file rather than at the beginning. It throws an IOException i.e, Input or Output Exception.

Syntax for creating object:

FileWriter f = new FileWriter(File f, boolean ap);

FileWriter (FileDescriptor fdes):It creates or generates a file writer object which is associated with the file descriptor.

Syntax for creating object:

FileWriter f = new FileWriter(FileDescriptor fdes);

FileWriter (String fN):It creates or generates a file writer object, given the file name.

Syntax for creating object:

FileWriter f = new FileWriter(String fN);

FileWriter (String fN, Boolean ap): It creates or generates a file writer object given a file name, it indicates whether to append or not to append the data written.

Syntax for creating object:

FileWriter f = new FileWriter(String fN, Boolean ap);

FileWriter (File f, Charset chset):  It creates or generates the file object when the file and charset are available.

Syntax for creating object:

 FileWriter f = new FileWriter(File f, Charset chset);

FileWriter (File f, Charset chset, boolean ap): It creates or generates the file object when the file and charset are given and if the argument is true then it appends to the end of the file rather than the beginning.

Syntax for creating object:

FileWriter f = new FileWriter(File f, Charset chest, boolean ap); 

FileWriter (String fN, Charset chest, boolean ap): It creates a file object when file and charset are given.

Syntax for creating object:

FileWriter f = new FileWriter(String fN, Charset chest, boolean ap);

Methods in File Writer:

  • write (int n)
  • write (String s1, int pos1, int si)
  • write (char c[], int po1, int si)

write (int n):
It is used to write a single character of data. The return type is a void, it overrides the write method which is present in the Writer class. It accepts only one parameter i.e, Integer type. It throws IOException which is an Input / Output Exception when an error occurs in Input or Output.

Syntax:

public void write(int n)

Program:

import java.io.FileWriter;
  
class Example1 {
  
    public static void main(String args[])
    {
  
        String data = "Welcome to Javatpoint";
          try {
            FileWriter output = new FileWriter("output.txt");
            output.write(data);
            output.close();
        }
  
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Output:

Welcome to Javatpoint

Here, the string is written into the file output.txt then the output.txt file contains Welcome to Javatpint.

write (String s1, int pos1, int si):

It is used to write the part of the string when it is passed through the Writer stream. It throws Input / Output Exception and Index out of bounds exception. I/O Exception occurs when errors are present in Input or Output, Index Out of bounds exception occurs when the negative length is passed through write method or length greater than string.

Syntax:

public int read(String s1, int pos1, int si)
  • s1 -It is the Destination buffer
  • pos1 – at which index it starts writing characters.
  • si -.Several characters

Program:

import java.io.*;
  class C{
    public static void main(String[] args) 
    {
   String s1 = “Welcome to JavaTpoint”
     try {
            FileWriter output = new FileWriter("output.txt");
            output.write(s1,0,4);
            output.close();
        }
  
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Output:

Welcome

write (char c[], int po1, int si):

It writes the characters from a particular array. , it directly uses the main Stream. It throws Input / Output Exception and Index out of bounds exception. I/O Exception occurs when errors are present in Input or Output, Index Out of bounds exception occurs when the negative length is passed through write method or length greater than an array.

Syntax:

public int read(char[] c, int po1, int si)
  • c -It is the Destination buffer
  • po1 – at which index it starts writing characters.
  • si -.Several characters

Program:

import java.io.*;
  class C{
    public static void main(String[] args) 
    {
   char ch[] = [‘W’,’E’,’L’,’C’,’O’,’M’,’E’];
     try {
            FileWriter output = new FileWriter("output.txt");
            output.write(ch,0,2);
            output.close();
        }
  
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Output:

WE

Related Topics

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Repdigit Numbers in Java

A combination of repeated and digit, the term is. A repdigit, also known as a monodigit or a positional number system, is a natural number in recreational mathematics made up...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

How to create array of objects in Java

Java is an object-oriented programming language therefore everything in Java is based on objects and classes. Array is a data structure that holds data of similar type and dynamically creates...

4 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.