Java Program to write into a file using CHARACTER STREAM .
Objective
Write a Java program to write text into a file using Character Streams.
Algorithm / Approach
- Prompt the user for a filename and string data.
- Inside a
tryblock, initialize aFileWriter. - Directly pass the String to
fw.write(data). - Close the writer in the
finallyblock.
WriteFile.java
import java.io.*;
import java.util.*;
class WriteFile {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter File Name: ");
String fileName = s.nextLine();
FileWriter fw = null;
try {
fw = new FileWriter(fileName);
System.out.print("Enter Data: ");
String data= s.nextLine();
fw.write(data);
System.out.println("Written successfully");
}
catch(IOException e){
System.out.print(e);
}
finally {
try {
fw.close();
}
catch(Exception e) {
System.out.print(e);
}
}
}
}
Expected Output
Enter File Name: Alok.txt Enter Data: Java Prowess is developed by Java, Android Trainer Written successfully
Explanation of the Program
- Character Streams (classes ending in
ReaderorWriter) handle data 16 bits (2 bytes) at a time, specifically matching the size of a Javachar(which uses UTF-16 Unicode). - Because they are designed specifically for text, they are much easier to use for writing strings. Notice that we didn't need to convert the String to a byte array—
FileWriterhandles the character encoding automatically.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)