This website is for reference purposes only. Users are responsible for any misuse. The owner is not liable for any consequences.
Back to Java Programming (Laboratory)
1.7.1HardCODE

Input and Output Streams

Question

Solution

JAVA

import java.io.*;
import java.util.Scanner;
public class IOStreamExample {
    public static void main(String[] args) {
        // File paths for input and output files
        System.out.print("file name:");
       Scanner sc = new Scanner(System.in);
       String inputFile = sc.nextLine();
        String outputFile = "output.txt";
        
        // Create InputStream and OutputStream objects
        FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;

        try {
            // Create FileInputStream to read data from the input file
            fileInputStream = new FileInputStream(inputFile);
            
            // Create FileOutputStream to write data to the output file
            fileOutputStream = new FileOutputStream(outputFile);

            int content;
            // Read each byte from the input file and write it to the output file
            while ((content = fileInputStream.read()) != -1){
                fileOutputStream.write(content);
            }
            // Reading from the output file and printing its contents
            FileInputStream outputFileStream = new FileInputStream(outputFile);
            StringBuilder outputContent = new StringBuilder();
            while ((content = outputFileStream.read()) != -1) {
                outputContent.append((char) content);
            }
			System.out.println("Contents of the output file:");
            System.out.print(outputContent.toString());

            // Close the output file stream
            outputFileStream.close();

        } 
        catch (IOException e) {
            System.out.println("No such file");
        } finally {
            try {
                // Close the streams to release resources
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                System.err.println("Error while closing streams: " + e.getMessage());
            }
        }
    }
}

3/3 test cases passed

2/2 hidden test cases passed