← Back to Core Java Course | Chapter 12: File I/O | Lesson 5 of 9

Java में FileReader और FileWriter

FileWriter एक file में text लिखता है और FileReader वापस text पढ़ता है, एक notebook में लिखने और इससे पढ़ने जैसा। यह एक समय में एक character काम करता है।
Syntax
java
FileReader reader = new FileReader("file_name");
FileWriter writer = new FileWriter("file_name");
writer.write("text");
writer.close();

Writing Characters with FileWriter

FileWriter एक file में character data लिखता है, Java की internal char/String data को लिखते समय अपने आप platform के default text encoding में convert करते हुए।

उदाहरण: Writing Characters with FileWriter

java
// Import java.io.FileWriter so it can be used by its short name
import java.io.FileWriter;
// Import java.io.IOException so it can be used by its short name
import java.io.IOException;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws IOException {
		// Create a new FileWriter object and store it in writer
		FileWriter writer = new FileWriter("notes.txt");
		writer.write("Hello");
		writer.close();
		// Print a line to the console
		System.out.println("Written");
	}
}

Reading Characters with FileReader

FileReader उसी तरह एक file से character data वापस पढ़ता है, पढ़ते समय डिस्क पर bytes को Java char values में convert करते हुए — text को round-tripping करने के लिए naturally FileWriter के साथ जोड़ा जाता है।

उदाहरण: Reading Characters with FileReader

java
// Import java.io.FileWriter so it can be used by its short name
import java.io.FileWriter;
// Import java.io.FileReader so it can be used by its short name
import java.io.FileReader;
import java.io.IOException;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws IOException {
		// Create a new FileWriter object and store it in writer
		FileWriter writer = new FileWriter("notes.txt");
		writer.write("Hi");
		writer.close();
		// Create a new FileReader object and store it in reader
		FileReader reader = new FileReader("notes.txt");
		int c;
		// Repeat while (c = reader.read()) != -1 is true
		while ((c = reader.read()) != -1) {
			// Print to the console without a newline
			System.out.print((char) c);
		}
		reader.close();
	}
}

Try-With-Resources cleanup

Try-with-resources उपयोग करना (try (FileWriter fw = new FileWriter(...)) {...}) गारंटी देता है कि file block exit होने पर अपने आप बंद हो, भले ही बीच में एक exception throw हो।

उदाहरण: Try-With-Resources cleanup

java
import java.io.FileWriter;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException {
		try (FileWriter writer = new FileWriter("notes.txt")) { // auto-closed on exit
			writer.write("Hello");
		}
		System.out.println("Closed automatically");
	}
}

File Handling Safety

File operations को हमेशा proper exception handling और resource closing में wrap करें — एक unclosed file handle resources leak कर सकता है, और एक program जो mid-write crash हो जाए वह एक file को corrupted, half-written state में छोड़ सकता है।

उदाहरण: File Handling Safety

java
// Import java.io.FileWriter so it can be used by its short name
import java.io.FileWriter;
// Import java.io.IOException so it can be used by its short name
import java.io.IOException;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Try code that might throw an exception
		try (FileWriter writer = new FileWriter("notes.txt")) {
			writer.write("Hello");
		// Handle IOException if it was thrown
		} catch (IOException e) {
			// Print a line to the console
			System.out.println("Handled safely: " + e.getMessage());
		}
	}
}

Dynamic Text Manipulation

चूंकि FileWriter default रूप से character-by-character लिखता है, इसे एक loop के साथ combine करना जो strings build और rewrite करता है किसी file की text content को fly पर transform करने का एक natural तरीका है।

उदाहरण: Dynamic Text Manipulation

java
// Import java.io.FileWriter so it can be used by its short name
import java.io.FileWriter;
// Import java.io.IOException so it can be used by its short name
import java.io.IOException;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws IOException {
		// Create a new StringBuilder object and store it in content
		StringBuilder content = new StringBuilder();
		// Loop: repeat while the condition holds
		for (int i = 1; i <= 3; i++) {
			content.append("Line ").append(i).append("\n");
		}
		// Try code that might throw an exception
		try (FileWriter writer = new FileWriter("notes.txt")) {
			writer.write(content.toString());
		}
		// Print a line to the console
		System.out.println("Written dynamically");
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना append mode के FileWriter उपयोग करना, जो मौजूदा text overwrite करता है।
  2. Writer बंद करना भूल जाना, इसलिए text save नहीं हो सकता।
  3. Binary files के लिए FileReader उपयोग करना, जो data corrupt करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.