Content to be covered:
- 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
Watch this video for a hands-on explanation and deeper insights:
Introduction of Java File Handling
- 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.
How to create a file?
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();
Read the content of a file and print it over the console
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);
}
Read the input from the console and write it into a file
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();
}
Write new data in existing file {Append data}
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();
}
How to count the number of characters in a file?
int c;
while ((c = bf.read()) != -1) {
chars++;
}
System.out.println("Chars: " + chars);
How to count the number of lines in a file?
int c;
while ((c = bf.read()) != -1) {
if ((char) c == '\n') {
lines++;
}
}
System.out.println("Lines: " + lines);
How to count the number of words in a file?
int c;
int words=0;
while ((c = bf.read()) != -1) {
if ((char) c == ' ' || (char) c == '\n') {
words++;
}
}
words++;
System.out.println("Words: " + words);
FileInputStream and FileOutputStream?
- 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();
How to read and write a file (byte by byte)?
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);
}
Questions for Practice:
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?
Java File Handling Project: Java Notes Manager
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:
- 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! - Display the existing Java note (read and display file content on the console).
- 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. - 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)
- Analyze the “JavaFile1.txt” note, providing:
- Total number of characters?
- Total number of lines?
- Total number of words?
- 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.
- Hint:
Thanks and Regards.
Sir in the assignment submission form only pdf submission option is available am unable to submit my archive file