Complete Guide to Java File Handling with Practice Questions

  • Introduction of Java File Handling
  • How to create a file?
  • How to read the input from the console and write it into a file?
  • How to read the content of a file and print it over the console?
  • How to write new data in existing file {Append data}?
  • How to count the number of characters in a file?
  • How to count the number of lines in a file?
  • How to count the number of words in a file?
  • How to read and write a file (byte by byte)?
  • What will happen if we directly use FileWriter.write(s1) instead of BufferedWriter.write(s1) method?
  • Java File Handling Project: Java Notes Manager
  • In Java, file handling is a fundamental aspect of many applications, allowing them to read from and write to files on the file system.
  • File handling in Java is a crucial functionality for developers, especially when dealing with large files. In this article, we’ll explore the concept of Java File Handling in a simplified manner.
  • The java.io.* package provides access to various classes for implementing file-handling techniques.
  • Reasons to apply file handling:
    • Store the computed results of previous executions.
    • Read data from a file instead of the console. Hence user dependency can be managed.
    • logs can be maintained with timestamps.
    • Backup and Recovery
  • Types of operations we can perform over a file:
    • Read class: Just to read, can not write into this file
    • Write class: we can write into this file but after every write old data will be lost.
    • Append class: we can write into this file but this time old data will not be lost.
String path = "src/FirstModule/file1.txt";
File file = new File(path);
		
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

String s1 = "Java";
bw.write(s1);

bw.close();
fw.close();
FileReader fr = new FileReader(path);
BufferedReader bf = new BufferedReader(fr);

//Approach-1
int c;
while ((c = bf.read()) != -1) {
	System.out.print((char) c);
}

//Approach-2
String line;
while ((line = br.readLine()) != null) {
	System.out.println(line);
}
System.out.println("Enter s1 string");

Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();

System.out.println(s1);

FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

try {
	bw.write(s1);
} catch (IOException e) {
	e.printStackTrace();
}
System.out.println("Enter s1 string");

Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();

System.out.println(s1);

FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);

try {
	bw.write(s1);
} catch (IOException e) {
	e.printStackTrace();
}
int c;
while ((c = bf.read()) != -1) {
	chars++;
}
System.out.println("Chars: " + chars);
int c;
while ((c = bf.read()) != -1) {

	if ((char) c == '\n') {
		lines++;
	}

}
System.out.println("Lines: " + lines);
int c;
int words=0;
while ((c = bf.read()) != -1) {

	if ((char) c == ' ' || (char) c == '\n') {
		words++;
	}
}
words++;
System.out.println("Words: " + words);
  • Transfer the content of one file to another file.
  • To read raw binary data (e.g., images, audio, PDF).
  • It reads one byte at a time, making it ideal for non-text files.
  • Binary Files Handling – Essential for handling images, videos, executables, or encrypted files where data must be preserved exactly.
// Reading a file using FileInputStream
FileInputStream fis = new FileInputStream("input.jpg");
FileOutputStream fos = new FileOutputStream("output.jpg");

int byteData;
while ((byteData = fis.read()) != -1) {
    fos.write(byteData); // write byte by byte
}

fis.close();
fos.close();
try {
File inputFile = new File("file1.txt");
File outputFile = new File("file2.txt");

FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile);
//FileOutputStream fos = new FileOutputStream(outputFile, true); // if you do not want to lose old data

int c;

while ((c = fis.read()) != -1) {
	System.out.print((char)c);
	fos.write(c);
}

fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.err.println("FileStreamsTest: " + e);
} catch (IOException e) {
System.err.println("FileStreamsTest: " + e);
}

Note: Create a package name “filepracticequestions” inside src and solve these questions (Q1.java and so on)

Q1. Write a Java program to create a new file named example.txt and check if it is successfully created.
Q2. Write a program to write the text “Hello, Java File Handling!” into a file.
Q3. Write a Java program to read and print the contents of a text file.
Q4. Create a program that counts the number of lines, words, and characters in a given text file.
Q5. Create a program that searches for a specific word in a file and prints its occurrences.
Q6. What will happen if we directly use FileWriter.write(s1) instead of BufferedWriter.write(s1) method?


Project Overview:
Develop a Java Notes Manager that allows users to create, update, and analyze text-based notes efficiently. This application will enable users to:

  1. Create a new Java note “JavaFile1.txt” (enter the given text from the console and save it to this file)

    Java is an object-oriented programming language.
    It supports encapsulation, inheritance, and polymorphism.
    File handling in Java allows for efficient reading and searching of text.
    Keep learning and mastering Java!


  2. Display the existing Java note (read and display file content on the console).
  3. Create another Java note “JavaFile2.txt” and (enter the given text from the console and save it to this file)
    This is the first line in this JavaFile2.txt file.

  4. Read the content of Java note “JavaFile1.txt” and copy it to “JavaFile2.txt” using file steams. (Keep the previous text intact and add it from the next line)
  5. Analyze the “JavaFile1.txt” note, providing:
    • Total number of characters?
    • Total number of lines?
    • Total number of words?
  6. Search for the word “polymorphism” in “JavaFile1.txt” and print the line number where it appears and also find the total occurrences of this word in this file.
    • Hint:
      • Read each line using ‘fileobj.readLine()’ until ‘null’.
      • Check if ‘line.contains(wordToFind)’.
      • Increment a counter to track the line number when found.

Thanks and Regards.

1 Comment.

  1. Sir in the assignment submission form only pdf submission option is available am unable to submit my archive file

Leave a Reply

Your email address will not be published. Required fields are marked *