A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/file-handling-java-using-filewriter-filereader/ below:

File handling in Java using FileWriter and FileReader

File handling in Java using FileWriter and FileReader

Last Updated : 11 Sep, 2023

Java FileWriter and FileReader classes are used to write and read data from text files (they are Character Stream classes). It is recommended not to use the FileInputStream and FileOutputStream classes if you have to read and write any textual information as these are Byte stream classes.
 

FileWriter
FileWriter is useful to create a file writing characters into it. 


Constructors: 


Methods: 


Reading and writing take place character by character, which increases the number of I/O operations and affects the performance of the system.BufferedWriter can be used along with FileWriter to improve the speed of execution.
The following program depicts how to create a text file using FileWriter
 

Java
// Creating a text File using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
    public static void main(String[] args) throws IOException
    {
        // Accept a string 
        String str = "File Handling in Java using "+
                " FileWriter and FileReader";

        // attach a file to FileWriter 
        FileWriter fw=new FileWriter("output.txt");

        // read character wise from string and write 
        // into FileWriter 
        for (int i = 0; i < str.length(); i++)
            fw.write(str.charAt(i));

        System.out.println("Writing successful");
        //close the file 
        fw.close();
    }
} 

FileReader

FileReader is useful to read data in the form of characters from a ‘text’ file. 


Constructors: 


Methods: 


The following program depicts how to read from the ‘text’ file using FileReader
 

Java
// Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
    public static void main(String[] args) throws IOException
    {
        // variable declaration
        int ch;

        // check if File exists or not
        FileReader fr=null;
        try
        {
            fr = new FileReader("text");
        }
        catch (FileNotFoundException fe)
        {
            System.out.println("File not found");
        }

        // read from FileReader till the end of file
        while ((ch=fr.read())!=-1)
            System.out.print((char)ch);

        // close the file
        fr.close();
    }
}


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4