×

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 Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java String charAt() method

It returns the char value present in the string at the specified index. Here, index value can not be greater than length() -1. Syntax: public char charAt (int index) Parmeters It accepts only...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

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.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.