Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Writing to files using writeString()
3.
Writing to files using FileWriter Class
4.
Writing to files using Buffered Class
5.
Writing to files using FileOutputStream Class
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

How to write on files in java

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

Introduction

In java, there is a character-oriented class named FileWriter. This class is used to write character-oriented information in a file. This is the reason why this is used in file handling. We can take the help of various ways to write files in java language. The approaches are given below:

  1. writeString()
  2. FileWriter Class
  3. Buffered Class
  4. FileOutputStream Class
     

Now, lets learn about each one of them with the assistance of their respective codes.

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

Writing to files using writeString()

This method is used when the data-covered data in file is less.

writeString() can have four parameters namely charset, character sequence, file path, and options. File path and character sequence are a must to write into a file. It can have four kinds of exceptions. It takes a character as the data of file and outputs file path.

Let's see a code of how to use it.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
    public static void main(String[] args) throws IOException {
        String data = "Example for writeString()";


        //Specifying path for the file.
        Path Filename = Path.of("writeFile.txt");


        //to write the content in the file
        Files.writeString(Filename, data);


        //to read the content fromt the file
        String content = Files.readString(Filename);


        //to print the content of the file
        System.out.println(content);
    }
}

 

Output:

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

Writing to files using FileWriter Class

This method can also be used if the data inside the file is less. It is a better option than writeString(). It takes a set of characters as the data of file. It should always close with close().

Let us understand it by the help of code.

// Java Program to Write into a File with the help of FileWriterClass
import java.io.FileWriter;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        //data to write in the file
        String data = "Java is hard but fun enough too";
        try {
            //creating a file object
            FileWriter fw = new FileWriter("myfiles.txt");
            //writing data into the file
            fw.write(data);
            System.out.println("Operation completed.");
            // closing the file
            fw.close();
        } catch (IOException e) {
            System.out.print(e.getMessage());
        }
    }
}

 

Output:

Writing to files using Buffered Class

Buffered class is used to write text file into character-output steam. It has its own assigned size, but it can be changed and made larger. It helps in writing bigger and larger files. It is helpful when it comes to writing characters, arrays, strings. 

Let's see the code of it.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        String data = "Welcome to Coding Ninja";
        try {
            BufferedWriter file_name = new BufferedWriter(new FileWriter("myfile.txt"));
            file_name.write(data);
            System.out.println("Operation completed");
            file_name.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

 

Output:

Try it by yourself on Java Online Compiler.

Must Read: Java System Out Println

Writing to files using FileOutputStream Class

This class is used to write a fresh set of data into a file. FileOutputStream class can be used to binary data. In this method, the string data is changed into a byte array, which is written with the help of write().

Let us understand it with the help of an example:

import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        String data = "Welcome to Coding Ninja";
        try {
            FileOutputStream resultdata = new FileOutputStream("myfile.txt");
            byte[] byteFromStr = data.getBytes();
            resultdata.write(byteFromStr);
            System.out.print("Operation completed.");
        } catch (IOException e) {
            System.out.print(e.getMessage());
        }
    }
}

 

Output:

 

 

Frequently Asked Questions

  1. What is the Scanner method in Java?
    A scanner is a class in (java.util package) that is used to get input of primitive types like double, int, and strings. It's the straightforward way to read input in a Java program, but it is inefficient if you need an input method for situations where time is a constraint, such as competitive programming.
     
  2. What is a switch in Java?
    In Java, the "switch" statement is a multi-way branch statement, often known as the switch case. Different parts of code can be performed fast based on the value of the expression specified. A primitive data-type, such as int, char, short, and byte can be used in the provided phrase.
     
  3. Which method is used to write into a file in Java?
    It also requires the creation of a class object with the filename in order to write data to a file. The content of the string is converted into a byte array, which is then written to the file using the write() method.

Conclusion

In this blog, we have discussed about how to write on files in java along with different ways like writeString(), FileWriter Class, Buffered Class, FileOutputStream Class, and its codes. 

We hope that this blog has helped you enhance your knowledge regarding how to write on files using java 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 Handling in Java
Next article
Delete a file using Java
Live masterclass