A few Sample Problems

The following programs are based on file reading and writing. Please use the following text file to test the following FIVE programs. I have created a video that i hope that you will find useful to run these scripts.

Sample File data.txt

data.txt

Line 1: Welcome to Java File IO
Line 2: Learning Java Streams
Line 3: Understanding FileInputStream
Line 4: Exploring FileOutputStream
Line 5: Mastering FileReader
Line 6: Utilizing FileWriter
Line 7: Efficient File Handling
Line 8: Data Processing in Java
Line 9: Java I/O Best Practices
Line 10: Working with Buffered Streams
Line 11: File Encryption Techniques
Line 12: File Decryption Process
Line 13: Advanced File Operations
Line 14: Stream Chaining Concepts
Line 15: Error Handling in File IO
Line 16: Java File and Directory Management
Line 17: Implementing Data Streams
Line 18: Understanding PrintStream
Line 19: File Copy Utilities in Java
Line 20: Java Serialization and Deserialization
Line 21: Character Set Encoding
Line 22: Managing Large Files
Line 23: Java Network Stream Handling
Line 24: System.in and System.out in Java
Line 25: End of File IO Exercises

Program - 01

Create a class FileLineCounter that reads a file and counts the number of lines in it. The program enters through the class App.java and should prompt the user to enter the name of the file and then display the total number of lines present in the file.

Class and Method Names

  • Class Name: FileLineCounter
  • Method Name: countLines(String filename)
  • Main Class Name: App

Expected Output for a Given Input

  • Input: "data.txt"
  • Output: "The file 'data.txt' contains 25 lines."

Program: FileLineCounter.java

import java.io.FileInputStream;
import java.io.IOException;

public class FileLineCounter {
    
    public int countLines(String filename) throws IOException {
        int lineCount = 0;
        int byteRead;
        try (FileInputStream fis = new FileInputStream(filename)) {
            while ((byteRead = fis.read()) != -1) {
                if (byteRead == '\n') {
                    lineCount++;
                }
            }
        }
        return lineCount;
    }
}

Program: App.java

import java.io.IOException;
// Main class to run the program
public class App
{
  public static void main (String[]args)
  {
	FileLineCounter counter = new FileLineCounter ();
	String filename = "data.txt";	// This can be replaced with user input
	  try
	{
	  int lines = counter.countLines (filename);
	    System.out.println ("The file '" + filename + "' contains " + lines +
							" lines.");
	} catch (IOException e)
	{
	  System.out.println ("An error occurred while reading the file: " +
						  e.getMessage ());
	}
  }
}

Program - 02

Create a class FileContentPrinter that reads a file and prints its content to the console. The program enters through the class App.java and should prompt the user to enter the name of the file, then display the file's content.

Class and Method Names

  • Class Name: FileContentPrinter
  • Method Name: printFileContent(String filename)
  • Main Class Name: App

Expected Output for a Given Input

  • Input: "data.txt"
  • Output: Prints the content of data.txt to the console.

Program: FileContentPrinter.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileContentPrinter {

    public void printFileContent(String filename) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

Program: App.java

import java.io.IOException;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        FileContentPrinter printer = new FileContentPrinter();
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the file name to print its content: ");
        String filename = scanner.nextLine();
        scanner.close();

        try {
            printer.printFileContent(filename);
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}

Program - 03

Create a class SpecificLineReader that reads a specific line from a file based on the line number provided by the user. The program should be executed from the App.java class, which prompts the user for the file name and the line number, and then displays the content of the specified line in the file.

Class and Method Names

  • Class Name: SpecificLineReader
  • Method Name: readSpecificLine
  • Main Class Name: App

Expected Output for a Given Input

  • Input: Filename (e.g., "data.txt") and line number
  • Output: The content of the specified line in the file

Program: SpecificLineReader.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class SpecificLineReader {

    public String readSpecificLine(String filename, int lineNumber) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            int currentLine = 1;
            while ((line = reader.readLine()) != null) {
                if (currentLine == lineNumber) {
                    return line;
                }
                currentLine++;
            }
        }
        return null; // Line not found
    }
}

Program: App.java

import java.io.IOException;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        SpecificLineReader lineReader = new SpecificLineReader();
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter the file name: ");
        String filename = scanner.nextLine();

        System.out.print("Enter the line number to read: ");
        int lineNumber = scanner.nextInt();
        scanner.close();

        try {
            String specificLine = lineReader.readSpecificLine(filename, lineNumber);
            if (specificLine != null) {
                System.out.println("Line " + lineNumber + ": " + specificLine);
            } else {
                System.out.println("Line " + lineNumber + " not found in the file.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}

Program 4: FileWordCounter

Create a class FileWordCounter that reads a file and counts the number of words in it. The program should be executed from the App.java class, which prompts the user for the file name and then displays the total number of words present in the file.

Class and Method Names

  • Class Name: FileWordCounter
  • Method Name: countWords
  • Main Class Name: App

Expected Output for a Given Input

  • Input: Filename (e.g., "data.txt")
  • Output: Count of words in the file

Program: FileWordCounter.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileWordCounter {

    public int countWords(String filename) throws IOException {
        int wordCount = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] words = line.split("\\s+");
                wordCount += words.length;
            }
        }
        return wordCount;
    }
}

Program: App.java

import java.io.IOException;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        FileWordCounter wordCounter = new FileWordCounter();
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the file name to count words: ");
        String filename = scanner.nextLine();
        scanner.close();

        try {
            int wordCount = wordCounter.countWords(filename);
            System.out.println("The file '" + filename + "' contains " + wordCount + " words.");
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}

Program 5: FirstLastLinePrinter

Create a class FirstLastLinePrinter that reads a file and prints the first and last lines of the file. The program should be executed from the App.java class, which prompts the user for the file name and then displays the first and last lines of the file.

Class and Method Names

  • Class Name: FirstLastLinePrinter
  • Method Name: printFirstLastLine
  • Main Class Name: App

Expected Output for a Given Input

  • Input: Filename (e.g., "data.txt")
  • Output: First and last lines of the file

Program: FirstLastLinePrinter.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FirstLastLinePrinter {

    public void printFirstLastLine(String filename) throws IOException {
        String firstLine = null;
        String currentLine;
        String lastLine = null;

        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            while ((currentLine = reader.readLine()) != null) {
                if (firstLine == null) {
                    firstLine = currentLine;
                }
                lastLine = currentLine;
            }
        }

        if (firstLine != null) {
            System.out.println("First line: " + firstLine);
            System.out.println("Last line: " + lastLine);
        } else {
            System.out.println("The file is empty.");
        }
    }
}

Program: App.java

import java.io.IOException;
import java.util.Scanner;

public class App {
    public static void main(String[] args) {
        FirstLastLinePrinter linePrinter = new FirstLastLinePrinter();
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the file name to print first and last lines: ");
        String filename = scanner.nextLine();
        scanner.close();

        try {
            linePrinter.printFirstLastLine(filename);
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file: " + e.getMessage());
        }
    }
}