1. Write a program to read and write a text file using FileReader and FileWriter (Character Stream)?
Algorithm :
- Start
- Initialize FileReader and FileWriter:
- Create FileReader reader for reading from source.txt.
- Create FileWriter writer for writing to destination.txt.
- Start Reading and Writing:
- Use a while loop to read each character from source.txt using reader.read().
- For each character read, write it to destination.txt using writer.write(character).
- Handle Exceptions:
- If an IOException occurs during reading or writing, it will be caught in the catch block, and the error details will be printed.
- Close the Streams:
- In the finally block, ensure both reader and writer are properly closed to release resources, even if an error occurs.
- Completion Message:
- After successfully copying content, print a message: “File written successfully using FileReader and FileWriter.”.
- End
Program :
import java.io.*; public class ReadWriteFileCharacterStream { public static void main(String[] args) { FileReader reader = null; FileWriter writer = null; try { reader = new FileReader(“source.txt”); writer = new FileWriter(“destination.txt”); int character; while ((character = reader.read()) != -1) { writer.write(character); } System.out.println(“File written successfully using FileReader and FileWriter.”); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
Output :
File written successfully using FileReader and FileWriter. |
Explanation :
This Java program demonstrates how to read from one file and write to another using FileReader and FileWriter, which handle file content character by character. It first creates instances of FileReader and FileWriter for reading from source.txt and writing to destination.txt. Inside a while loop, it reads each character from the source file and writes it to the destination file. If any IOException occurs during this process, it is caught and the stack trace is printed. Finally, the program ensures that both the reader and writer are closed in the finally block to prevent resource leaks. When the file writing operation is completed, a success message is displayed. |
2. Write a program to append content to an existing file using FileWriter?
Algorithm :
- Start
- Initialize FileWriter in Append Mode:
- Create a FileWriter instance for the file output.txt, with the second argument true to enable append mode.
- Append Content:
- Use writer.write(“\nThis is an appended line.”) to append the new line to the end of the file. The \n ensures that the appended text starts on a new line.
- Handle Exceptions:
- If an IOException occurs during file writing, the exception will be caught and its stack trace will be printed.
- Close the Writer:
- In the finally block, ensure that the FileWriter is properly closed to release resources.
- Completion Message:
- After successfully appending the content, print the message “Content appended successfully.”.
- End
Program :
import java.io.*; public class AppendToFile { public static void main(String[] args) { FileWriter writer = null; try { writer = new FileWriter(“output.txt”, true); writer.write(“\nThis is an appended line.”); System.out.println(“Content appended successfully.”); } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
Output :
Content appended successfully. |
Explanation :
The AppendToFile program demonstrates how to append content to an existing file using FileWriter in Java. The program opens output.txt in append mode by passing true as the second argument to the FileWriter constructor, ensuring that new data is added to the end of the file without overwriting it. It appends a new line of text: “This is an appended line.” using writer.write(). If an IOException occurs, it is caught and printed. After the operation, the FileWriter is closed to release system resources, and a success message is printed to confirm the successful operation. |
3. Write a program to read a file using BufferedReader and count occurrences of a specific word?
Algorithm :
- Start
- Initialize Resources:
- A BufferedReader object reader is created to read the file source.txt using FileReader.
- A string wordToCount is set to “Java”, and an integer wordCount is initialized to 0 to keep track of the word occurrences.
- Read File Line by Line:
- The program enters a while loop, reading the file line by line with reader.readLine().
- Split Line into Words:
- For each line, it splits the text into words using the regular expression \\s+ (whitespace delimiter).
- Check Each Word:
- The program then checks each word in the array to see if it matches “Java”, ignoring case with equalsIgnoreCase().
- If a match is found, wordCount is incremented by 1.
- Display Word Count:
- After all lines are processed, the total count of occurrences of the word “Java” is printed to the console.
- Close Resources:
- In the finally block, the BufferedReader is closed to release resources, ensuring that the file is properly closed even if an exception occurs.
- End
Program :
import java.io.*; public class CountWordOccurrences { public static void main(String[] args) { BufferedReader reader = null; String wordToCount = “Java”; int wordCount = 0; try { reader = new BufferedReader(new FileReader(“source.txt”)); String line; while ((line = reader.readLine()) != null) { // Counting occurrences of the word String[] words = line.split(“\\s+”); for (String word : words) { if (word.equalsIgnoreCase(wordToCount)) { wordCount++; } } } System.out.println(“The word ‘” + wordToCount + “‘ appears ” + wordCount + ” times.”); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } |
Output :
The word ‘Java’ appears 5 times. |
Explanation :
The program begins by initializing a BufferedReader to read from the file source.txt . It sets the target word to "Java" and initializes a counter variable to track its occurrences. The program reads the file line by line using a while loop. Each line is split into individual words based on whitespace. For every word, it checks if it matches "Java" (ignoring case), and if so, increments the counter. After processing the entire file, it prints the total count and closes the file safely. |
4. Write a program to write an object to a file using ObjectOutputStream (Object Serialization)?
Algorithm :
- Start
- Create a Serializable Class:
- Define a class Person and implement Serializable to enable object serialization.
- Initialize Object:
- Create an instance of Person with name “John” and age 25.
- Setup Output Stream:
- Use ObjectOutputStream with FileOutputStream to write the object to a file named person.ser.
- Serialize the Object:
- Call writeObject(person) to serialize and write the object to the file.
- Handle Exceptions:
- Catch and print any IOException that might occur.
- Close Resources:
- Use try-with-resources to ensure the ObjectOutputStream is automatically closed.
- End
Program :
import java.io.*; class Person implements Serializable { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return “Person{name='” + name + “‘, age=” + age + “}”; } } public class ObjectSerialization { public static void main(String[] args) { Person person = new Person(“John”, 25); try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“person.ser”))) { // Writing object to file out.writeObject(person); System.out.println(“Object serialized successfully.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
Object serialized successfully. |
Explanation :
The program defines a Person class that implements the Serializable interface, allowing its instances to be serialized. It creates a Person object with the name “John” and age 25. Using ObjectOutputStream wrapped around a FileOutputStream, it writes this object to a file named person.ser. This process converts the object into a byte stream suitable for file storage. The use of try-with-resources ensures that the output stream is closed automatically. Serialization is useful for saving object state or sending objects over a network. |
5. Write a program to deserialize an object from a file using ObjectInputStream?
Algorithm :
- Start
- Define a Serializable Class:
Create a class Person that implements the Serializable interface so its objects can be saved and restored from a file. - Declare Fields and Constructor:
Define instance variables name and age. Create a constructor to initialize these variables. - Override toString() Method:
Override the toString() method to return a formatted string representation of a Person object. - Open File for Reading:
In the main() method, create an ObjectInputStream wrapped around a FileInputStream pointing to the file “person.ser”. - Deserialize the Object:
Use in.readObject() to read the serialized object and cast it to Person. - Display the Object:
Print the deserialized object using System.out.println(). - End
Program :
import java.io.*; class Person implements Serializable { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return “Person{name='” + name + “‘, age=” + age + “}”; } } public class ObjectDeserialization { public static void main(String[] args) { try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(“person.ser”))) { Person person = (Person) in.readObject(); System.out.println(“Deserialized Person: ” + person); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } |
Output :
Deserialized Person: Person{name=’John’, age=25} |
Explanation :
This program demonstrates Java object deserialization by restoring a previously saved Person object from the file person.ser. The Person class implements Serializable, allowing its objects to be serialized and deserialized. In the main method, an ObjectInputStream is created to read the binary data from the file. The object is read using readObject(), which returns a generic Object, so it is cast to Person. The deserialized object’s contents are then printed using the overridden toString() method. Exception handling ensures any I/O or class mismatch errors are caught and printed. |
6. Write a program to write an array of primitive types to a file using DataOutputStream?
Algorithm :
- Start
- Open a Binary Output Stream:
- Create a DataOutputStream object wrapped around a FileOutputStream to write data to the file data.bin.
- Write an Integer:
- Use writeInt(100) to write the integer value 100 in binary format to the file.
- Write a Double:
- Use writeDouble(45.67) to write the double value 45.67 in binary format.
- Write a UTF String:
- Use writeUTF(“Hello, Java!”) to write the string “Hello, Java!” in a UTF-encoded format.
- Print Confirmation:
- Display a message “Data written successfully.” to confirm that the write operations completed.
- Handle Exceptions:
- Catch and print any IOException that may occur during the file writing process.
- End
Program :
import java.io.*; public class DataOutputExample { public static void main(String[] args) { try (DataOutputStream out = new DataOutputStream(new FileOutputStream(“data.bin”))) { out.writeInt(100); out.writeDouble(45.67); out.writeUTF(“Hello, Java!”); System.out.println(“Data written successfully.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
Data written successfully. |
Explanation :
This Java program demonstrates how to write various primitive data types to a binary file using DataOutputStream. It opens a file named data.bin for output and writes an integer, a double, and a UTF-encoded string. Each value is written in a machine-readable binary format that preserves its type and precision. The use of a try-with-resources block ensures the output stream is properly closed after writing. This approach is efficient for storing and transmitting data in binary form. If any input/output error occurs, it is caught and printed to the console. |
7. Write a program to read data from one file and write it to another using Byte Streams?
Algorithm :
- Start
- Open Input Stream:
- Create a FileInputStream to read bytes from the file source.txt.
- Open Output Stream:
- Create a FileOutputStream to write bytes to the file destination.txt.
- Read and Write Loop:
- Use a while loop to read bytes one by one from source.txt until the end of file (indicated by -1) is reached.
- Write Each Byte:
- For every byte read, write the same byte to destination.txt using fos.write(data).
- Close Streams Automatically:
- The try-with-resources statement ensures both streams are automatically closed after operations are complete.
- Handle Errors:
- Catch and handle any IOException that might occur during reading or writing.
- End
Program :
import java.io.*; public class ByteStreamExample { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream(“source.txt”); FileOutputStream fos = new FileOutputStream(“destination.txt”)) { int data; while ((data = fis.read()) != -1) { fos.write(data); } System.out.println(“File copied successfully using Byte Streams.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied successfully using Byte Streams. |
Explanation :
The program demonstrates file copying using byte streams in Java. It uses a FileInputStream to read raw bytes from source.txt and a FileOutputStream to write those bytes to destination.txt. Each byte is read and written one at a time in a loop until the end of the file is reached. This approach is ideal for binary files or low-level I/O operations. The try-with-resources block ensures that file streams are closed automatically, preventing resource leaks. If any exception occurs during the process, it is caught and printed to help with debugging. |
8. Write a program to copy a file using BufferedInputStream and BufferedOutputStream for efficiency?
Algorithm :
- Start
- Open Buffered Input Stream:
- Create a BufferedInputStream connected to source.txt for efficient byte reading.
- Open Buffered Output Stream:
- Create a BufferedOutputStream connected to destination.txt for efficient byte writing.
- Read and Write Loop:
- Read bytes from the input stream using bis.read() and write them to the output stream using bos.write(data) until the end of the file (-1) is reached.
- Use Internal Buffer:
- Buffered streams use an internal buffer, reducing the number of physical I/O operations for better performance.
- Close Streams Automatically:
- Use the try-with-resources statement to ensure automatic closing of streams after the operation.
- Handle I/O Exceptions:
- Catch any IOException that might occur during the file operations and print the stack trace.
- End
Program :
import java.io.*; public class BufferedByteStreamExample { public static void main(String[] args) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(“source.txt”)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“destination.txt”))) { int data; while ((data = bis.read()) != -1) { bos.write(data); } System.out.println(“File copied successfully with buffering.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied successfully with buffering. |
Explanation :
The program demonstrates how to efficiently copy a file using buffered byte streams. BufferedInputStream and BufferedOutputStream wrap around low-level streams to reduce the number of direct disk access operations by using an internal buffer. This improves performance, especially for large files. The program reads and writes each byte inside a loop until the end of the source file is reached. Using a try-with-resources block ensures that all streams are properly closed after the operation. If any IOException occurs during file I/O, it’s caught and printed to assist in troubleshooting. |
9. Write a program to read and write data to a file using Character Streams?
Algorithm :
- Start
- Initialize FileReader:
- Open the source.txt file using FileReader to read character data.
- Initialize FileWriter:Open the destination.txt file using FileWriter to write character data.
- Read and Write Loop:
- Continuously read characters using fr.read() and write them using fw.write(data) until the end of file (-1) is reached.
- Use Try-with-Resources:
- Automatically close the reader and writer using the try-with-resources block to avoid resource leaks.
- Display Success Message:
- Print a confirmation message once the file copying is complete.
- Handle Exceptions:
- Catch and handle any IOException that may occur during file operations.
- End
Program :
import java.io.*; public class CharacterStreamExample { public static void main(String[] args) { try (FileReader fr = new FileReader(“source.txt”); FileWriter fw = new FileWriter(“destination.txt”)) { int data; while ((data = fr.read()) != -1) { fw.write(data); } System.out.println(“File copied successfully using Character Streams.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied successfully using Character Streams. |
Explanation :
This program demonstrates copying text from one file to another using character streams. It uses FileReader to read characters from the source file and FileWriter to write those characters to the destination file. The loop reads one character at a time and writes it, ensuring all contents are duplicated. Character streams are ideal for handling text data, especially when dealing with Unicode. The use of try-with-resources ensures the streams are closed automatically. Any I/O errors encountered during the process are caught and printed for debugging purposes. |
10. Write a program to read a file line by line using BufferedReader?
Algorithm :
- Start
- Initialize BufferedReader:
- Create a BufferedReader object by wrapping it around a FileReader linked to source.txt.
- Read Line-by-Line:
- Use readLine() in a loop to read the file one line at a time until null is returned (end of file).
- Print Each Line:
- Output each line to the console using System.out.println().
- Use Try-with-Resources:
- Automatically manage resource closing with the try-with-resources block.
- Catch IOException:
- Catch and handle any exceptions that may occur during file operations.
- End
Program :
import java.io.*; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader(“source.txt”))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } |
Output (assuming source.txt contains multiple lines of text):
Line 1 of the file Line 2 of the file Line 3 of the file |
Explanation :
The program reads a text file line by line using a BufferedReader, which improves performance by reducing disk access through internal buffering. It wraps a FileReader to read from source.txt and uses the readLine() method to fetch one line at a time. Each line is printed to the console until the end of the file is reached. This approach is efficient for reading large text files. The try-with-resources ensures that the file stream is properly closed after execution. Any IOException that arises is caught and displayed to help in debugging. |
11. Write a program to Write data to a file using BufferedWriter?
Algorithm :
- Start the Program:
- The program begins execution in the main method.
- Create a BufferedWriter:
- The program creates a BufferedWriter wrapped around a FileWriter that points to the file destination.txt.
- This allows writing data to the file efficiently by buffering the output.
- Write Data to the File:
- The BufferedWriter writes the string “Hello, this is a test line.” to the file using the write() method.
- After writing the first line, the program inserts a new line using the newLine() method.
- Then, the program writes “This is another line.” to the file.
- Close the BufferedWriter:
- The BufferedWriter is automatically closed after the write operations due to the try-with-resources statement. This ensures the proper closing of the file and releases any associated resources.
- Catch IOException:
- If an IOException occurs during file writing (such as if the file cannot be opened or written to), the program catches the exception and prints the stack trace.
- Output Message:
- After the data is written to the file, the program prints a success message “Data written to file using BufferedWriter.” to the console.
- End of Program:
- The program completes execution after writing the content and printing the success message.
Program :
import java.io.*; public class BufferedWriterExample { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(“destination.txt”))) { bw.write(“Hello, this is a test line.”); bw.newLine(); bw.write(“This is another line.”); System.out.println(“Data written to file using BufferedWriter.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
Data written to file using BufferedWriter. |
Explanation :
In this program, the BufferedWriter class is used to efficiently write data to a file named destination.txt. First, a BufferedWriter is created by wrapping it around a FileWriter for the target file. This allows for buffered writing, which optimizes file I/O operations by reducing the number of write calls. The program then writes a line of text, “Hello, this is a test line.”, followed by a newline character using the newLine() method, and then writes another line, “This is another line.”. After writing, the BufferedWriter is automatically closed due to the try-with-resources statement, ensuring that system resources are properly released. If any errors occur during writing, such as file access issues, they are caught by the IOException handler, and the stack trace is printed for debugging. Finally, a message confirming successful data writing is displayed on the console. |
12. Write a program to efficient file copy using BufferedInputStream and BufferedOutputStream?
Algorithm :
- Start
- Create BufferedInputStream and BufferedOutputStream:
- Create a BufferedInputStream (bis) using the FileInputStream that reads data from the source file (source.txt).
- Create a BufferedOutputStream (bos) using the FileOutputStream to write data to the destination file (destination.txt).
- Buffer Allocation:
- Declare a byte array (buffer) of size 1024 bytes to hold data read from the source file before writing it to the destination file.
- Reading and Writing Data:
- Enter a while loop where data is read from the source file using bis.read(buffer). The method reads up to 1024 bytes of data and returns the number of bytes read.
- Write the data into the destination file using bos.write(buffer, 0, length), where length is the number of bytes read.
- File Copying Completion:
- The loop continues until all data from the source file has been read and written into the destination file.
- After the copy operation is completed, print the success message “File copied successfully using Buffered Streams.”.
- Exception Handling:
- Any IOException encountered during reading, writing, or closing streams is caught and its stack trace is printed.
- Close Streams Automatically:
- The try-with-resources statement ensures that both BufferedInputStream and BufferedOutputStream are automatically closed after the file copying process is completed.
- End
Program :
import java.io.*; public class FileCopyWithBufferedStreams { public static void main(String[] args) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(“source.txt”)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(“destination.txt”))) { byte[] buffer = new byte[1024]; int length; while ((length = bis.read(buffer)) != -1) { bos.write(buffer, 0, length); } System.out.println(“File copied successfully using Buffered Streams.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied successfully using Buffered Streams. |
Explanation :
The program copies a file’s contents from source.txt to destination.txt using buffered streams for efficient I/O operations. It creates a BufferedInputStream to read data and a BufferedOutputStream to write data. Data is read in chunks of 1024 bytes into a buffer, which is then written to the destination file. The program continues reading and writing until all data is copied. The use of buffered streams improves performance compared to byte-by-byte reading and writing. The try-with-resources statement ensures that the streams are automatically closed after the operation. If any errors occur, they are handled by the IOException catch block. |
13. Write a program to convert an InputStream to a Reader with a specific encoding and write it to a file?
Algorithm :
- Start
- Open the Source File:
- Open the source file (source.txt) using a FileInputStream wrapped with an InputStreamReader to handle character encoding (UTF-8).
- Open the Destination File:
- Open the destination file (destination.txt) using a FileWriter to write data into the file.
- Read Data from Source File:
- Use a while loop to continuously read characters from the source file. The read() method of InputStreamReader reads one character at a time from the file in UTF-8 encoding.
- Write Data to Destination File:
- For each character read from the source file, write the same character to the destination file using FileWriter.
- Check End of File:
- Close the Streams Automatically:
- The try-with-resources statement ensures that both the InputStreamReader and FileWriter are automatically closed after the file operations are complete.
- Print Success Message:
- After completing the file copying process, print the success message “File copied with encoding conversion.” to indicate the operation was successful.
- End
Program :
import java.io.*; public class EncodingConversionExample { public static void main(String[] args) { try (InputStreamReader reader = new InputStreamReader(new FileInputStream(“source.txt”), “UTF-8”); FileWriter writer = new FileWriter(“destination.txt”)) { int data; while ((data = reader.read()) != -1) { writer.write(data); } System.out.println(“File copied with encoding conversion.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied with encoding conversion. |
Explanation :
This program performs file copying with encoding conversion. It uses an InputStreamReader to read characters from the source file (source.txt) with UTF-8 encoding, ensuring that characters are correctly interpreted based on their encoding. The program then writes the characters to a new file (destination.txt) using a FileWriter, which by default uses the system’s character encoding. The process reads one character at a time from the source file and writes it to the destination file until the end of the file is reached. The try-with-resources ensures proper closing of both input and output streams. In case of any errors, an IOException is caught and printed. |
14. Write a program to read from a file and write to another file using FileInputStream and FileOutputStream (Byte Streams)?
Algorithm :
- Start
- Open File Streams:
- Create a FileInputStream to read from “source.txt” and a FileOutputStream to write to “destination.txt”.
- Read Byte-by-Byte:
- Use a loop to read bytes one at a time from the source file.
- Write Each Byte:
- Each byte read is immediately written to the destination file using the output stream.
- Repeat Until End:
- The loop continues until fis.read() returns -1, which indicates the end of the file.
- Print Confirmation:
- Print a success message after the copying is completed.
- Handle Exceptions:
- Any IOException is caught and its details are printed.
- Auto-Close Resources:
- The try-with-resources ensures the streams are closed automatically.
- End
Program :
import java.io.*; public class ByteStreamReadWrite { public static void main(String[] args) { try (FileInputStream fis = new FileInputStream(“source.txt”); FileOutputStream fos = new FileOutputStream(“destination.txt”)) { int data; while ((data = fis.read()) != -1) { fos.write(data); } System.out.println(“File copied successfully using Byte Streams.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output :
File copied successfully using Byte Streams. |
Explanation :
This Java program demonstrates copying a file using byte streams. It reads the contents of “source.txt” byte by byte and writes them to “destination.txt”. The use of FileInputStream and FileOutputStream allows for efficient handling of binary data. Each byte is read from the input stream and directly written to the output stream in a loop. The try-with-resources block ensures that both streams are closed automatically, preventing resource leaks. This method is suitable for copying any kind of file—text or binary. If an error occurs, it is safely handled and printed. |
15. Write a program to write an array of bytes to a file using FileOutputStream?
- Start
- Create File Output Stream:
- A FileOutputStream is created for the file destination.txt to write byte data.
- Prepare Byte Data:
- A byte array data is defined containing {65, 66, 67, 68} which correspond to ASCII values of characters ‘A’, ‘B’, ‘C’, ‘D’.
- Write Bytes to File:
- The write() method of FileOutputStream writes all bytes from the data array to the file.
- Display Confirmation:
- A message “Bytes written to file.” is printed to confirm successful writing.
- Handle Exceptions:
- If an IOException occurs, it is caught and its details are printed.
- Auto-Close Stream:
- The try-with-resources block ensures the file output stream is automatically closed.
- End
Program :
import java.io.*; public class WriteBytesExample { public static void main(String[] args) { try (FileOutputStream fos = new FileOutputStream(“destination.txt”)) { byte[] data = {65, 66, 67, 68}; // ASCII values for A, B, C, D fos.write(data); System.out.println(“Bytes written to file.”); } catch (IOException e) { e.printStackTrace(); } } } |
Output (contents of destination.txt will be:) :
ABCD |
Explanation :
The program writes raw byte data to a file using a FileOutputStream. It defines a byte array with ASCII values of characters A, B, C, and D, then writes this array to destination.txt. This results in the file containing the text ABCD. Using try-with-resources, the file stream is automatically closed after writing. This approach is efficient for writing binary or encoded character data. If any I/O error occurs, it is safely caught and printed. The program is a simple demonstration of byte-level file writing in Java. |