Java Text File Handling: Write, Append, Read and Process (ISC Class 11)
Updated 17 October 2026 · Fact-checked
A text file stores characters permanently. In Java, FileWriter writes characters to a file (new FileWriter(name, true) appends), FileReader reads characters, and BufferedReader reads whole lines with readLine(), which returns null at the end of the file. File operations can throw IOException, which must be handled with try-catch or declared with throws. Programs commonly count lines, words and characters, find totals and search for a word.
FileWriter sends data to the file (true means append), BufferedReader reads line by line until null, and every step must handle IOException.
Illustration drawn for QuestionBuddy.
Understand Text Files in Java: Create, Write, Append, Read, Search and Count
Need for files. Variables and arrays lose their values when the program ends; a file stores data permanently on disk and allows large data to be processed.
Writing.
import java.io.*;
FileWriter fw = new FileWriter("data.txt"); // creates or overwrites
fw.write("Java is fun");
fw.write("\n"); // new line
fw.close(); // always close
FileWriter fa = new FileWriter("data.txt", true); // append modePrintWriter pw = new PrintWriter(new FileWriter("data.txt")); pw.println("text"); pw.close(); is also used.
Reading.
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();readLine() returns one line without the newline, and null at the end of the file. FileReader's read() returns the next character as an int, or -1 at the end.
Exceptions. IOException (and FileNotFoundException when reading a missing file) must be handled: either wrap in try { } catch (IOException e) { } or write throws IOException after the method header.
Processing file data.
- *Count lines:* increase a counter in the read loop.
- *Count words:* use a StringTokenizer on each line (countTokens()).
- *Count characters:* sum line.length() (excluding newline characters).
- *Total, maximum, average:* convert each line with Integer.parseInt(line.trim()).
- *Search:* test line.indexOf(word) >= 0 or line.contains(word).
Modes. Overwrite (default) replaces old contents; append keeps them and adds at the end.
Text Files in Java: Create, Write, Append, Read, Search and Count: key facts
- Write and read classes
FileWriter write FileReader read characters BufferedReader readLine - java.io package.
- End of file
- readLine() returns null | read() returns -1
- Loop condition.
- Modes
- new FileWriter(name): overwrite | new FileWriter(name, true): append
- Constructor argument.
How to answer Text Files in Java: Create, Write, Append, Read, Search and Count questions
Open, process in a loop until end of file, close.
- 1Import java.io and handle IOException.
- 2Open the file (reader or writer).
- 3Loop with readLine() until null, updating counters.
- 4Close the file and print the results.
Text Files in Java: Create, Write, Append, Read, Search and Count in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Append vs overwrite
Suppose a shop logs each day's sale to a file "sales.txt" and, by mistake, uses new FileWriter("sales.txt") each day.
What happens to earlier days' data and how is it avoided?
Try it first, then show the solutionSolution
- The default mode overwrites: earlier data are lost.
- Use new FileWriter("sales.txt", true) to append.
Answer: Earlier data are lost; append mode avoids it.
Memory hook: True means keep the old.
Tricks to remember Text Files in Java: Create, Write, Append, Read, Search and Count
Short memory aids. Say each one aloud once, then use it on a question the same day.
null ends the line loop
readLine() returns null at end.
Use it when: Read loop.
true appends
Second argument true keeps old contents.
Use it when: Append.
Close it
Close writers so data are saved.
Use it when: Closing.
Text Files in Java: Create, Write, Append, Read, Search and Count: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Append · 1 mark · MCQBoard level
To add new text at the end of an existing file without erasing it, you create:
(a) new FileWriter("a.txt") (b) new FileWriter("a.txt", true) (c) new FileReader("a.txt") (d) new File("a.txt")
Try it first, then show the solutionSolution
- The second argument true selects append mode.
Answer: (b) new FileWriter("a.txt", true)
Example 2: Count lines, words and characters · 6 marks · Long answerBoard level
The file data.txt contains three lines:
Java is fun
I like code
Bye
Write a program segment to count the lines, words and characters (excluding newline characters) and give the output. (6 marks)
Try it first, then show the solutionSolution
- Read each line; lines++; words += new StringTokenizer(line).countTokens(); chars += line.length().
- Line 1: 3 words, 11 characters; line 2: 3 words, 11 characters; line 3: 1 word, 3 characters.
- Totals: 3 lines, 7 words, 25 characters.
Answer:
Output: 3 7 25BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
int lines = 0, words = 0, chars = 0;
while ((line = br.readLine()) != null) {
lines++;
words += new StringTokenizer(line).countTokens();
chars += line.length();
}
br.close();
System.out.println(lines + " " + words + " " + chars);
Example 3: Total, maximum and average · 6 marks · Long answerHarder board level
A file marks.txt has one integer per line: 12, 15, 9, 20. Write the segment to find the sum, the maximum and the average, and give the output. (6 marks)
Try it first, then show the solutionSolution
- Parse each line with Integer.parseInt(line.trim()).
- sum = 12 + 15 + 9 + 20 = 56; max = 20; count = 4.
- average = 56.0 / 4 = 14.0.
Answer:
Output: 56 20 14.0int sum = 0, max = Integer.MIN_VALUE, n = 0;
while ((line = br.readLine()) != null) {
int x = Integer.parseInt(line.trim());
sum += x; n++;
if (x > max) max = x;
}
System.out.println(sum + " " + max + " " + (double) sum / n);
Example 4: Search · 5 marks · Long answerHarder board level
Write a program segment to display the lines containing the word "is" and the number of such lines, for the file whose lines are: Java is fun / I like code / This is easy / Bye. State the output. (5 marks)
Try it first, then show the solutionSolution
- Test line.indexOf("is") >= 0 for each line.
- Line 1 "Java is fun" contains "is". Line 2 "I like code" does not. Line 3 "This is easy" contains "is" (also inside "This"). Line 4 "Bye" does not.
- Count = 2.
Answer: Java is fun
This is easy
2 (the condition line.indexOf("is") >= 0 also matches "is" inside "This").
Example 5: Debug a file program · 4 marks · Short answerHOTS / competency
A student writes: FileWriter fw = new FileWriter("log.txt"); fw.write("Day1"); and the file is empty after the run. A second program calls new FileWriter("log.txt") each day and loses old entries. Identify the faults and give the corrected statements. (4 marks)
Try it first, then show the solutionSolution
- Fault 1: the writer was not closed (or flushed), so buffered data were not written; add fw.close();.
- Fault 2: the default constructor overwrites; use new FileWriter("log.txt", true) to append.
- Both must also handle IOException with try-catch or throws.
Answer: Close the writer (fw.close()), use append mode new FileWriter("log.txt", true), and handle IOException.
Where students lose marks in Text Files in Java: Create, Write, Append, Read, Search and Count
The slips examiners see most often, and what to write instead.
Mistake: Forgetting IOException
File operations can fail.
Wrong working
No try-catch or throws
Right working
throws IOException
Do this: Declare or handle it.
Usually costs: 1-2 marks.
Mistake: Looping with while (br.readLine() != null) then using readLine() again
Skipping a line.
Wrong working
Two readLine() calls
Right working
while ((line = br.readLine()) != null)
Do this: Store the line in the loop condition.
Usually costs: 2 marks.
Mistake: Not closing the file
Data may not be saved.
Wrong working
No close()
Right working
br.close() / fw.close()
Do this: Close in the end.
Usually costs: 1 mark.
Exam tips
- Always write the import java.io.* and the exception handling.
- Show the read loop with a stored line variable.
- State the expected output for the sample file.
Practice questions on Text Files in Java: Create, Write, Append, Read, Search and Count
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
In a read loop, readLine() returns which value at the end of the file?
(a) -1 (b) "" (c) null (d) 0Hint
A reference value.
Answer
(c) null
Q2 · 3 marks · Short answerBoard level
Write a code segment to create a file "names.txt" and store the three names Asha, Bilal and Chitra, one per line. (3 marks)
Hint
PrintWriter or FileWriter.
Answer
PrintWriter pw = new PrintWriter(new FileWriter("names.txt")); pw.println("Asha"); pw.println("Bilal"); pw.println("Chitra"); pw.close(); (inside a method that handles IOException).
Q3 · 5 marks · Long answerHarder board level
A file holds words, one per line: apple, kiwi, banana, fig, grape. Write a segment that prints the longest word and the number of words that have more than 4 letters, and state the output. (5 marks)
Hint
Lengths 5, 4, 6, 3, 5.
Answer
Track the longest while reading with line.length(). Output: banana 3 (apple 5, banana 6 and grape 5 have more than 4 letters; kiwi has 4 and fig has 3).
Q4 · 5 marks · Long answerHarder board level
A file "temp.txt" has the readings 21, 25, 18, 30, 26. Write a segment that finds and prints how many readings are above the average and the average. State the output. (5 marks)
Hint
Sum = 120.
Answer
Read all values into an array (or read the file twice). Sum = 120; average = 24.0. Readings above 24: 25, 30, 26 = 3. Output: 3 24.0
Q5 · 3 marks · Short answerHOTS / competency
A program appends a record to a file but each run shows only the latest record in the file. Another reads the file and prints one line less than it holds. Identify the likely cause of each. (3 marks)
Hint
Mode and loop.
Answer
The first program uses the default overwrite mode instead of append (new FileWriter(name, true)). The second calls readLine() twice per iteration (once in the loop condition and again inside), skipping a line.
Test your recall
Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.
1.Class for appending text?Show answer
FileWriter with true.
2.readLine() at end?Show answer
Returns null.
3.Which exception?Show answer
IOException.
4.Count words with?Show answer
StringTokenizer countTokens().
5.Why close a file?Show answer
To save data and release it.
Text Files in Java: Create, Write, Append, Read, Search and Count: frequently asked questions
Is the file created if absent?
FileWriter creates it.
What if a file to read is missing?
FileNotFoundException.
Does readLine() include the newline?
No.
Package for file classes?
java.io.