Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is FileWriter?
3.
Constructors of FileWriter
4.
Methods of FileWriter
5.
Frequently Asked Questions
5.1.
Write the difference between FileWriter and FileOutputStream.
5.2.
What is the alternative for File writers?
5.3.
What is the advantage of FileWriter?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

FileWriter

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java's FileWriter provides the simplest way to write a file. You can write string, byte array, and int to the File via the overloaded write method. It is also possible to write parts of Strings or byte arrays with FileWriter. It is recommended to use FileWriter only when the number of writes is limited. So, let’s learn about Filewriter.

FileWriter

Also See, Multithreading in java, and Duck Number in Java.

What is FileWriter?

A very important class in the java.io package is the FileWriter class. This class allows us to write directly to files. We can write either text or character data to these files. Uses a default buffer size to write text to character files. A specific charset or the platform's default charset is used to encode characters into bytes.

The underlying platform determines whether or not a file is available or created. In particular, some platforms limit a single FileWriter from opening a file at once. If the file involved is already open, the constructors in this class will fail. FileWriter is designed to write streams of characters. If you need to write raw bytes, use a FileOutputStream.

What is FileWriter

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Constructors of FileWriter

We can perform operations on a file using various types of FileWriter constructors. By using a FileWriter class, we create an object that is a member of that class. 

  1. FileWriter f=new FileWriter(String Filename) 
    This constructor represents a file by overriding existing data in a file using a string representation of its name.
     
  2. FileWriter f=new FileWriter(File f)
    This constructor is used to pass a file reference, where the class "File" is passed.
     
  3. FileWriter f=new FileWriter(String filename, boolean append) 
    The constructor is used to append the data to an existing file. If you set the boolean to true, the data should be appended.
     
  4. FileWriter f=new FileWriter(File filename, boolean append) 
    The constructor works by taking a File object and constructing a FileWriter object. The second argument indicates that bytes should be written to the file's end, not the beginning.
     
  5. FileWriter f=new FileWriter(FileDescriptor fd) 
    This constructor creates a FileWriter object associated with a file descriptor.
     

Here is a java program to show how FileWriter class works

import java.io.FileWriter;
import java.io.IOException;
class Main {
    public static void main(String[] args) throws IOException {
        String data = "Tutorial for FileWriter";
        FileWriter file = new FileWriter("FileWriter.txt");
        try {
            file.write(data);
            System.out.println("content added to the file...");
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output:

Output

Methods of FileWriter

  • write(): Specifies a single character to be written.
  • write(char[] ar): This method writes the characters from an array to the writer.
  • write(String content): The writer is updated with the specified string.
  • flush(): A copy of all the data contained in the writer is written to the destination.
  • close(): The file writer is closed with this function. The writer cannot be used to write data after calling the close() method.
  • append(): This command inserts a specified character into the current writer.
  • getEncoding(): To determine the type of encoding used to write data, use the getEncoding().
     

Here is a java program implementation for the above methods

import java.io.FileWriter;
public class Main {
    public static void main(String args[]) {
        String data = "Hey Ninja's, here are the methods of Filewriter";
        try {
            // creating an object for file
            FileWriter file = new FileWriter("file.txt");

            // Writes the string to the file
            file.write(data);

            //getting the type of Encoding
            System.out.println("Character encoding of file: " + file.getEncoding());

            //adding content to end of the file
            file.append("...new content added");

            // Closing the file
            file.close();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}


Output:

Output

Frequently Asked Questions

Write the difference between FileWriter and FileOutputStream.

→In FileWriter, you write streams of characters, whereas, in FileOutputStream, raw bytes are written.
→It deals with characters that are 16-bits long, while FileOutputStream deals with bytes that are 8-bits long.
→Strings can be written to a file with FileWriter, whereas FileOutputStream writes bytes and does not accept characters. Therefore, it needs to be wrapped in OutputStreamWriter to contain strings.
 

What is the alternative for File writers?

→BufferedWriter: It uses internal buffers to write data to the File. When you need to perform any write operations, you should use this.
→FileOutputStream: It is used when writing raw stream data to the File instead of FileWriter and BufferedWriter since they are meant to write text.
→Files: We can use its write method to write a file. OutputStream writes a byte array into a file internally.

What is the advantage of FileWriter?

FileWriter is a Java class for writing character-oriented data to files. It is used for handling files. FileOutputStream class does not require you to convert a string into a byte array since it provides methods to write strings directly.

Conclusion

In this blog, we have seen how FileWriter class works in java, how to implement different types of constructors, and some methods of FileWriter.

We hope that this blog has helped you enhance your knowledge about FileWriter and if you would like to learn more, check out our articles on the link. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
File Reader
Next article
File Descriptor Class in Java
Live masterclass