Basic Input/Output and Text File Handling in Java: ISC 11
Updated 15 October 2026 · Fact-checked
Java reads keyboard input with the Scanner class, which splits the input stream into tokens separated by whitespace or user-defined delimiters, and StringTokenizer splits strings the same way. ISC Class 11 Computer Science also covers input/output exceptions and text files: creating, writing, appending, reading and searching them with FileWriter and FileReader.
What Basic Input/Output and Text File Handling is about
Programs need data from outside: values typed by a user, or records saved in a file from an earlier run. This chapter covers both: console input with Scanner and text files that keep data after the program ends.
The CISCE 2028 syllabus (Section B, topic 11) asks for: (a) basic input/output using the Scanner class; input/output exceptions; tokens in an input stream, the concept of whitespace, extracting tokens (StringTokenizer class); the Scanner class for input of various types of data; user-defined delimiters; and (b) data file handling: the need for data files, input stream, output stream, character streams (FileReader, FileWriter), and the operations of creation, reading, writing, appending and searching (text files only).
Four programs on this page were compiled and run, including a file program whose output shows the file before and after appending.
Weightage: Basic Input/Output and Text File Handling is topic 11 of the ISC Class XI Computer Science syllabus, in Section B - Java. CISCE weights Section B at 30 of the 70 marks in Paper I (Theory). Class XI is examined by the school, so your school sets the paper within this weightage.Source: CISCE ISC Computer Science syllabus, examination year 2028, Class XI unit weightage
Key concepts
- Streams, tokens and whitespace
A stream is a sequence of data flowing between a program and a source or destination.
- Input stream: data flows into the program (keyboard: System.in; a file).
- Output stream: data flows out of the program (screen: System.out; a file).
- Byte streams handle raw bytes; character streams (Reader and Writer classes such as FileReader and FileWriter) handle text as Unicode characters.
A token is a meaningful unit of input (a word or a number) separated from others by delimiters. By default the delimiter is whitespace: spaces, tabs (\t) and line breaks (\n). Multiple whitespace characters together count as one separator.
In the input line ' Java is fun ', there are 3 tokens: Java, is and fun.
User-defined delimiters let other characters separate tokens: commas in '82,75,91', slashes in a date '12/05/2026', colons in a time '10:20:30'.
Worked example
How many tokens are in 'I love Java programming' with whitespace delimiters, and in 'a,b,,c' with ',' as the delimiter? [1 mark]
Try it first, then show the solutionSolution
- Whitespace: I, love, Java, programming = 4 (the double space is one separator).
- Comma: a, b, c = 3 (empty tokens between two commas are skipped by StringTokenizer).
Answer: 4 and 3.
- The Scanner class for input of various types
Scanner (java.util) reads tokens from an input source and converts them to the required type.
Scanner sc = new Scanner(System.in);
Method Reads nextInt(), nextLong(), nextDouble(), nextFloat(), nextBoolean() the next token as that type next() the next token as a String (one word) nextLine() the rest of the current line, including spaces next().charAt(0) a single character hasNextInt(), hasNext(), hasNextLine() true if such input is available (without reading it) The nextLine trap: after nextInt() or nextDouble(), the line break is still waiting; a following nextLine() returns an empty string. Call an extra sc.nextLine() to consume it first.
InputMismatchException is thrown when the token does not match the requested type (typing 'ninety' for nextInt()). Catch it, then skip the bad token with next().
// Reading different types with Scanner, and handling a wrong input type. import java.util.Scanner; import java.util.InputMismatchException; public class ScannerDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.next(); // one token (stops at whitespace) int age = sc.nextInt(); double height = sc.nextDouble(); sc.nextLine(); // consume the rest of the line String city = sc.nextLine(); // whole line, spaces included System.out.println("name = " + name + ", age = " + age + ", height = " + height); System.out.println("city = " + city); try { int marks = sc.nextInt(); // the next token is 'ninety': not an int System.out.println("marks = " + marks); } catch (InputMismatchException e) { System.out.println("Not a whole number: " + sc.next()); // read and skip the bad token } int sum = 0, count = 0; while (sc.hasNextInt()) // read numbers until a non-number appears { sum += sc.nextInt(); count++; } System.out.println("read " + count + " numbers, sum = " + sum); } }Input:
Riya 16 1.62 New Delhi ninety 12 7 30 endOutput:
name = Riya, age = 16, height = 1.62 city = New Delhi Not a whole number: ninety read 3 numbers, sum = 49Worked example
For the input '5 apples 3.5' followed by a new line 'next line', what do nextInt(), next(), nextDouble(), nextLine() and another nextLine() return? [2 marks]
Try it first, then show the solutionSolution
- nextInt() → 5; next() → "apples"; nextDouble() → 3.5.
- nextLine() → "" (the rest of line 1 is empty); the second nextLine() → "next line".
Answer: 5, "apples", 3.5, "" and "next line".
- StringTokenizer and user-defined delimiters
StringTokenizer (java.util) breaks a String into tokens.
- new StringTokenizer(str): delimiters are whitespace.
- new StringTokenizer(str, delims): every character in delims is a delimiter (",;" means comma or semicolon).
- new StringTokenizer(str, delims, true): the delimiters are also returned as tokens.
Methods: countTokens() (tokens remaining), hasMoreTokens() (any left?), nextToken() (the next token as a String).
Scanner with a user-defined delimiter: sc.useDelimiter("/") makes Scanner split on slashes, so a date can be read with nextInt() three times.
Tokens are Strings; convert numbers with Integer.parseInt or Double.parseDouble.
// Tokens and delimiters: StringTokenizer with default and user-defined delimiters, // and Scanner with a user-defined delimiter. import java.util.StringTokenizer; import java.util.Scanner; public class Tokens { public static void main(String[] args) { String line = " Java is fun "; StringTokenizer st = new StringTokenizer(line); // whitespace is the delimiter System.out.println("tokens = " + st.countTokens()); while (st.hasMoreTokens()) System.out.print("[" + st.nextToken() + "]"); System.out.println(); String csv = "Asha,82,Mumbai;Bilal,75,Pune"; StringTokenizer rec = new StringTokenizer(csv, ",;"); // user-defined delimiters while (rec.hasMoreTokens()) System.out.print(rec.nextToken() + " | "); System.out.println(); StringTokenizer withDelims = new StringTokenizer("3+4-2", "+-", true); // return delimiters too while (withDelims.hasMoreTokens()) System.out.print("<" + withDelims.nextToken() + ">"); System.out.println(); Scanner sc = new Scanner("12/05/2026"); sc.useDelimiter("/"); // Scanner with a user-defined delimiter int d = sc.nextInt(), m = sc.nextInt(), y = sc.nextInt(); System.out.println("day " + d + ", month " + m + ", year " + y); } }Output:
tokens = 3 [Java][is][fun] Asha | 82 | Mumbai | Bilal | 75 | Pune | <3><+><4><-><2> day 12, month 5, year 2026Worked example
Using StringTokenizer with ':' as delimiter, convert the time '12:45:30' into seconds. [2 marks]
Try it first, then show the solutionSolution
- Tokens 12, 45, 30 → parseInt each.
- 12 × 3600 + 45 × 60 + 30 = 43,200 + 2,700 + 30 = 45,930.
Answer: 45,930 seconds.
- Need for data files; input/output exceptions
Why data files:
1. Permanent storage: variables are lost when the program ends; files keep data between runs.
2. Large data: thousands of records need not be typed each time.
3. Sharing: other programs (or people) can use the same data.
4. Records: marks, stock or attendance can be added over time.Text files store data as readable characters (lines of text), which can be opened in any editor; the syllabus uses text files only.
Input/output exceptions: file operations can fail at run time: the file may not exist, the disk may be full, or permission may be denied. Java reports these with IOException (java.io), a checked exception: code that opens, reads or writes files must either catch it (try-catch) or declare it (throws IOException). FileNotFoundException is a kind of IOException.
Closing: always close() a file when finished (ideally in finally) so that data is written out (flushed) and the file is released.
Worked example
Why must a method that uses FileReader either catch IOException or declare throws IOException? [1 mark]
Try it first, then show the solutionSolution
- IOException is a checked exception; the compiler insists that it be handled or declared.
Answer: Because IOException is checked: without a catch or a throws clause, the program does not compile.
- Text files: create, write, append, read, search
Writing (output stream):
- Create and write: FileWriter fw = new FileWriter("marks.txt"); fw.write("Asha 82\n"); fw.close(); creates the file, or overwrites it if it exists.
- Append: new FileWriter("marks.txt", true) adds to the end instead of overwriting.
Reading (input stream): wrap FileReader in BufferedReader to read whole lines:
BufferedReader br = new BufferedReader(new FileReader("marks.txt"));
readLine() returns the next line, or null at the end of the file; loop with while ((line = br.readLine()) != null).
Searching: read line by line and compare (equals, startsWith, indexOf); stop with break when found; report 'not found' after the loop.
// Text file handling with character streams: create and write, append, read, and search. import java.io.FileWriter; import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class TextFile { static final String FILE = "marks.txt"; static void create() throws IOException { FileWriter fw = new FileWriter(FILE); // creates (or overwrites) the file fw.write("Asha 82\n"); fw.write("Bilal 75\n"); fw.write("Chitra 91\n"); fw.close(); // flushes and releases the file } static void append(String record) throws IOException { FileWriter fw = new FileWriter(FILE, true); // true = append mode fw.write(record + "\n"); fw.close(); } static void display() throws IOException { BufferedReader br = new BufferedReader(new FileReader(FILE)); String line; int n = 0, total = 0; while ((line = br.readLine()) != null) // null means end of file { System.out.println(" " + line); total += Integer.parseInt(line.substring(line.indexOf(' ') + 1)); n++; } br.close(); System.out.println(" " + n + " records, average = " + (double) total / n); } static String search(String name) throws IOException { BufferedReader br = new BufferedReader(new FileReader(FILE)); String line, result = name + " not found"; while ((line = br.readLine()) != null) { if (line.startsWith(name + " ")) { result = "found: " + line; break; } } br.close(); return result; } public static void main(String[] args) { try { create(); System.out.println("After creating:"); display(); append("Dev 68"); System.out.println("After appending:"); display(); System.out.println(search("Chitra")); System.out.println(search("Esha")); BufferedReader br = new BufferedReader(new FileReader("missing.txt")); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); } } }Output:
After creating: Asha 82 Bilal 75 Chitra 91 3 records, average = 82.66666666666667 After appending: Asha 82 Bilal 75 Chitra 91 Dev 68 4 records, average = 79.0 found: Chitra 91 Esha not found IOException: missing.txt (The system cannot find the file specified)The last line shows the IOException caught when opening a file that does not exist (the exact message text depends on the operating system).
Worked example
A program writes 'one' to t.txt with new FileWriter("t.txt"), closes it, then writes 'two' with new FileWriter("t.txt") again. What does the file contain? How would you keep both lines? [2 marks]
Try it first, then show the solutionSolution
- The second FileWriter without true overwrites the file: it contains only 'two'.
- Use new FileWriter("t.txt", true) for the second write to append.
Answer: Only 'two'; open the second FileWriter in append mode (second argument true) to keep both.
- Processing file data: counting and statistics
Most file questions combine reading with processing:
1. Read each line with readLine().
2. Split the line into tokens (StringTokenizer, or indexOf and substring).
3. Convert numbers with parseInt or parseDouble.
4. Update counters, totals, maximums or search results.
5. After the loop, close the file and print the results.The program below writes three lines to notes.txt, then counts the lines, the words (using spaces, commas and full stops as delimiters) and the occurrences of 'water', ignoring case.
// Writes a short text file, then reads it back counting lines, words and occurrences of a word. import java.io.*; import java.util.StringTokenizer; public class WordStats { public static void main(String[] args) { String file = "notes.txt"; try { FileWriter fw = new FileWriter(file); fw.write("The water cycle moves water around the Earth.\n"); fw.write("Water evaporates, condenses and falls as rain.\n"); fw.write("Rain water fills rivers.\n"); fw.close(); BufferedReader br = new BufferedReader(new FileReader(file)); String line; int lines = 0, words = 0, hits = 0; while ((line = br.readLine()) != null) { lines++; StringTokenizer st = new StringTokenizer(line, " ,."); // spaces and punctuation while (st.hasMoreTokens()) { String w = st.nextToken(); words++; if (w.equalsIgnoreCase("water")) hits++; } } br.close(); System.out.println("lines = " + lines + ", words = " + words + ", 'water' = " + hits); } catch (IOException e) { System.out.println("File error: " + e.getMessage()); } } }Output:
lines = 3, words = 19, 'water' = 4Worked example
In WordStats, why are ',' and '.' included in the delimiters? [1 mark]
Try it first, then show the solutionSolution
- Without them, 'Earth.' and 'evaporates,' would be tokens with punctuation attached and 'water.' would not match 'water'.
Answer: So that punctuation is not counted as part of words, and words such as 'Earth.' match cleanly.
Basic Input/Output and Text File Handling in real life
Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Why files
Suppose your class's attendance program stores records only in variables, and the computer restarts every evening.
What happens to the attendance, and what is the fix?
Try it first, then show the solutionSolution
- Variables live in memory, which is cleared when the program ends.
- Writing records to a text file keeps them permanently; each day's records can be appended.
Answer: The data is lost; save it in a file (appending each day).
Memory hook: Memory forgets; files remember.
Delimiters
Imagine your teacher exports marks as a line like 'Asha,82,91,77'.
How would a program separate the name and the three marks?
Try it first, then show the solutionSolution
- Use StringTokenizer with ',' as the delimiter.
- First token is the name; parse the next three as ints.
Answer: Tokenise on commas and convert the marks with Integer.parseInt.
Memory hook: Choose the delimiter the data uses.
Overwriting by mistake
Suppose a shop's sales program opens sales.txt with new FileWriter("sales.txt") every time it records a sale.
What will the file contain at the end of the day?
Try it first, then show the solutionSolution
- Without append mode, each opening overwrites the file.
- Only the last sale remains.
Answer: Only the last sale; use new FileWriter("sales.txt", true) to append.
Memory hook: True to keep, false to wipe.
Topics in this chapter
Basic Input/Output and Text File Handling: syntax and key facts
- Scanner input
- Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String w = sc.next(); String line = sc.nextLine();
- StringTokenizer
- StringTokenizer st = new StringTokenizer(str, delims); while (st.hasMoreTokens()) st.nextToken();
- Write or append
- new FileWriter(name) overwrites; new FileWriter(name, true) appends
- Read lines
- BufferedReader br = new BufferedReader(new FileReader(name)); while ((line = br.readLine()) != null) { ... } br.close();
- Exceptions
File code try { ... } catch (IOException e) { ... } Or method ... throws IOException Scanner type errors InputMismatchException
Basic Input/Output and Text File Handling: diagrams to practise
Practise each one on paper: draw it from the checklist, then tick off every label.
Streams
Explain input and output streams.
Draw
- Left: sources (keyboard, file) with arrows labelled 'input stream' into a central box 'Java program'.
- Right: arrows labelled 'output stream' to destinations (screen, file).
- Label the classes: System.in / Scanner, FileReader / BufferedReader on the left; System.out, FileWriter on the right.
Label
- input stream
- output stream
- character stream
Watch out: Arrows show direction: input flows into the program, output flows out.
Tokenising a line
Explain tokens and delimiters.
Draw
- Write 'Asha,82,Mumbai;Bilal,75,Pune' with each delimiter (',' and ';') circled.
- Under it, boxes for each token in order: Asha | 82 | Mumbai | Bilal | 75 | Pune.
Label
- delimiter
- token
Watch out: Circle every delimiter character; it makes the token count obvious.
How the school exam asks Basic Input/Output and Text File Handling
The question patterns to expect, and the method that works for each.
| Question type | How it is asked | Method |
|---|---|---|
| Theory (1-2 marks) | Define token, delimiter, stream; why data files; checked IOException; next vs nextLine. | Definition plus a one-line example. |
| Output and tracing (2-5 marks) | Count tokens; predict Scanner results for given input; predict file contents after write and append. | Mark delimiters; remember nextLine after nextInt returns the rest of the line. |
| Programs (5-10 marks) | Create a file of records, append, read and display, search, or compute statistics. | Separate methods for create, append, display, search; handle IOException; close files. |
Tricks to remember Basic Input/Output and Text File Handling
Short memory aids. Say each one aloud once, then use it on a question the same day.
next = word, nextLine = rest of line
After nextInt, nextLine first eats the leftover line break.
Use it when: Scanner input.
has, then next
hasNextInt() checks; nextInt() takes.
Use it when: Safe input loops.
null means the end
readLine() returns null at end of file.
Use it when: Reading files.
Open, use, close
Every FileWriter and BufferedReader needs close().
Use it when: File handling.
Basic Input/Output and Text File Handling: exam-level solved questions
Ordered from exam level to HOTS. Cover the solution, write your own, then compare step by step.
Example 1: Default delimiter · 1 mark · MCQExam level
By default, Scanner and StringTokenizer separate tokens using:
(a) commas
(b) whitespace
(c) full stops
(d) semicolons
Try it first, then show the solutionSolution
- Spaces, tabs and line breaks are the default delimiters.
Answer: (b) whitespace.
Example 2: Append mode · 1 mark · Assertion-reasonHarder exam level
Assertion: new FileWriter("data.txt", true) keeps the existing contents of data.txt.
Reason: The second argument true opens the file in append mode.
(a) Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
(b) Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
(c) Assertion is true but Reason is false.
(d) Both Assertion and Reason are false.
Try it first, then show the solutionSolution
- Append mode writes after the existing text instead of replacing it: the Reason explains the Assertion.
Answer: (a)
Example 3: Tokens with delimiters · 2 marks · Short answerExam level
Give the output of: StringTokenizer st = new StringTokenizer("3+4-2", "+-", true); while (st.hasMoreTokens()) System.out.print("<" + st.nextToken() + ">");
Try it first, then show the solutionSolution
- Delimiters + and − are also returned because of true.
- Tokens in order: 3, +, 4, −, 2.
Answer: <3><+><4><-><2> (as the compiled Tokens program printed).
Example 4: Scanner with a mismatch · 5 marks · Short answerHarder exam level
Trace ScannerDemo for the input shown (Riya 16 1.62 / New Delhi / ninety / 12 7 30 end) and explain each output line.
Try it first, then show the solutionSolution
- next() → Riya; nextInt() → 16; nextDouble() → 1.62.
- sc.nextLine() consumes the rest of line 1 (empty); the next nextLine() reads 'New Delhi' including the space.
- nextInt() meets 'ninety': InputMismatchException is caught, and next() reads and prints the bad token.
- hasNextInt() loop reads 12, 7 and 30 (sum 49) and stops at 'end'.
- Output: name = Riya, age = 16, height = 1.62 / city = New Delhi / Not a whole number: ninety / read 3 numbers, sum = 49.
Answer: Four lines as shown by the compiled program; the extra nextLine and the mismatch handling are the key steps.
Example 5: File operations · 5 marks · Short answerHOTS / competency
Describe the TextFile program's create, append, display and search operations, and give the average printed after appending 'Dev 68'.
Try it first, then show the solutionSolution
- create: new FileWriter(FILE) writes three lines, overwriting any old file; close().
- append: new FileWriter(FILE, true) adds a line at the end.
- display: BufferedReader over FileReader; readLine() until null; parse the number after the space; count and total.
- search: readLine() until a line starts with the name and a space; break; else 'not found'.
- After appending: total = 82 + 75 + 91 + 68 = 316; average = 316 ÷ 4 = 79.0.
Answer: Average 79.0 for 4 records (the compiled program printed '4 records, average = 79.0').
Example 6: Word statistics in a file · 10 marks · Long answerHOTS / competency
Write a program that writes three lines of text to notes.txt, then reads the file and counts the lines, the words (treating spaces, commas and full stops as delimiters) and the occurrences of the word 'water' in any case. Handle file errors.
Try it first, then show the solutionSolution
- Create the file with FileWriter, write three lines ending with \n, close it.
- Open with BufferedReader(new FileReader(...)); while ((line = br.readLine()) != null) count lines.
- For each line, StringTokenizer st = new StringTokenizer(line, " ,."); count each token as a word.
- If token.equalsIgnoreCase("water"), increase hits.
- Close the file and print the counts; wrap everything in try-catch (IOException).
- Output (compiled program): lines = 3, words = 19, 'water' = 4.
Answer: See the compiled WordStats program in the processing section: lines = 3, words = 19, 'water' = 4.
Case-study practice (Section D style)
Read the situation, then answer every part. In a school exam set on the board pattern this is a 5-mark question split into 1 + 2 + 2 marks.
Canteen orders file
Suppose a school canteen's Java program records each order as a line 'roll,item,price' (for example '1123,Sandwich,40') in orders.txt during the day. At closing time it must print the total sales and the number of orders for 'Samosa'. Yesterday the file contained only the last order.
(i) · 1 mark
Why did the file contain only the last order, and how is it fixed?
Answer
Answer: Each order opened the file with new FileWriter("orders.txt"), which overwrites; use new FileWriter("orders.txt", true) to append.
1 mark.
(ii) · 2 marks
How should each line be split, and how is the price converted?
Answer
Answer: StringTokenizer(line, ",") gives roll, item and price tokens; Integer.parseInt(priceToken) converts the price for adding to the total.
1 mark tokenising, 1 mark parsing.
(iii) · 2 marks
If the lines are '1123,Sandwich,40', '1040,Samosa,15', '1201,Samosa,15' and '1180,Juice,30', what are the total and the Samosa count?
Answer
Answer: Total = 40 + 15 + 15 + 30 = ₹100; Samosa orders = 2.
1 mark each.
Where the marks are
How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.
Tokens with returned delimiters (2 marks) (2 marks)
| Step | Marks |
|---|---|
| Delimiters returned as tokens | 1 |
| Correct order and format of output | 1 |
Trace the file program (5 marks) (5 marks)
| Step | Marks |
|---|---|
| Create vs append explained | 2 |
| Reading loop to null | 1 |
| Search logic | 1 |
| Average after appending | 1 |
Word statistics program (10 marks) (10 marks)
| Step | Marks |
|---|---|
| Writing the file and closing | 2 |
| Reading loop with readLine | 2 |
| Tokenising with user-defined delimiters | 2 |
| Counting words and case-insensitive matches | 2 |
| Exception handling and output | 2 |
Where students lose marks in Basic Input/Output and Text File Handling
The slips examiners see most often, and what to write instead.
Mistake: Reading a line with nextLine right after nextInt
It returns the empty rest of the previous line.
Do this: Add an extra sc.nextLine() to consume the line break.
Usually costs: 1 mark.
Mistake: Forgetting append mode
new FileWriter(name) erases the existing file.
Do this: Use new FileWriter(name, true) to add records.
Usually costs: 1-2 marks.
Mistake: Not handling IOException
It is a checked exception; the program will not compile.
Do this: try-catch (IOException e) or throws IOException.
Usually costs: 1 mark.
Mistake: Forgetting to close the writer
Buffered data may never reach the file.
Do this: Call close() (in finally where possible).
Usually costs: 1 mark.
Practice questions on Basic Input/Output and Text File Handling
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 · MCQExam level
Which method of BufferedReader returns null at the end of a file?
(a) read()
(b) readLine()
(c) nextLine()
(d) close()Hint
Whole lines.
Answer
(b) readLine().
Q2 · 1 mark · Very short answerExam level
Name the exception thrown when nextInt() reads 'abc'.
Hint
Mismatch.
Answer
InputMismatchException.
Q3 · 2 marks · Short answerExam level
Distinguish between next() and nextLine() of Scanner.
Hint
Word vs line.
Answer
next() reads the next token (one word, stopping at whitespace). nextLine() reads the rest of the current line, including spaces, and consumes the line break.
Q4 · 1 mark · Very short answerHarder exam level
How many tokens are in '10:20:30' with the default delimiters, and with ':' as the delimiter?
Hint
No whitespace inside.
Answer
1 with the default (whitespace) delimiters; 3 with ':'.
Q5 · 2 marks · Short answerHarder exam level
Write a code segment that reads integers from a Scanner until a non-integer appears and prints their sum, and give the sum for the input '7 8 x 9'.
Hint
hasNextInt.
Answer
int sum = 0; while (sc.hasNextInt()) sum += sc.nextInt(); System.out.println(sum); For '7 8 x 9' it stops at x and prints 15.
Q6 · 2 marks · Short answerHarder exam level
State four reasons for using data files.
Hint
Permanent, large, shared, growing.
Answer
Permanent storage beyond the program's run; handling large amounts of data without retyping; sharing data among programs and users; keeping growing records (appending over time).
Q7 · 5 marks · Short answerHOTS / competency
Write a method void showAbove(String file, int cut) that reads lines 'name marks' and prints the names of students with marks above cut. What would it print for the marks file after appending (cut = 80)?
Hint
readLine, split at the space.
Answer
void showAbove(String file, int cut) throws IOException { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { int sp = line.indexOf(' '); int m = Integer.parseInt(line.substring(sp + 1)); if (m > cut) System.out.println(line.substring(0, sp)); } br.close(); } For Asha 82, Bilal 75, Chitra 91, Dev 68 and cut 80: Asha and Chitra.
Q8 · 2 marks · Short answerHarder exam level
Explain the difference between an input stream and an output stream, and name the character-stream classes used for text files.
Hint
Direction.
Answer
An input stream carries data into the program from a source (keyboard, file); an output stream carries data from the program to a destination (screen, file). For text files: FileReader (often wrapped in BufferedReader) for input and FileWriter for output.
Q9 · 10 marks · Long answerHOTS / competency
Write a program that stores 'name,phone' records in contacts.txt (creating it with three records), appends one more, and then searches for a name entered by the user, printing the phone number or 'not found'.
Hint
Methods for create, append, search.
Answer
create(): FileWriter fw = new FileWriter("contacts.txt"); write three lines such as "Asha,98100\n"; close. append(String rec): new FileWriter("contacts.txt", true); write rec + "\n"; close. search(String name): BufferedReader over FileReader; for each line, StringTokenizer st = new StringTokenizer(line, ","); String n = st.nextToken(), p = st.nextToken(); if (n.equalsIgnoreCase(name)) return p; after the loop return "not found"; close the reader. main(): call create and append, read the name with Scanner.nextLine(), print search(name); wrap in try-catch (IOException) to report file errors.
Q10 · 2 marks · Short answerHOTS / competency
What does the file contain after: FileWriter fw = new FileWriter("t.txt"); fw.write("one\n"); fw.close(); fw = new FileWriter("t.txt"); fw.write("two\n"); fw.close(); and what do two readLine() calls return?
Hint
Overwrite.
Answer
Only 'two'. The first readLine() returns "two" and the second returns null (end of file).
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.Default delimiter?Show answer
Whitespace.
2.StringTokenizer methods?Show answer
countTokens, hasMoreTokens, nextToken.
3.Append to a file?Show answer
new FileWriter(name, true).
4.End of file for readLine?Show answer
null.
5.Checked exception for files?Show answer
IOException.
6.Set a Scanner delimiter?Show answer
useDelimiter("...").
Best order to study it
- Streams, tokens and whitespace.
- Scanner methods; nextLine trap; InputMismatchException.
- StringTokenizer; user-defined delimiters.
- Need for files; IOException.
- Create, write, append, read, search.
- Processing file data.
Quick revision checklist
The night before the exam: can you do each of these without looking?
- Stream: input into the program, output out of it; character streams for text.
- Token: unit between delimiters; default whitespace.
- Scanner: nextInt, nextDouble, next, nextLine, hasNextInt; useDelimiter.
- StringTokenizer(str, delims[, true]): countTokens, hasMoreTokens, nextToken.
- FileWriter(name) overwrites; (name, true) appends; close().
- BufferedReader(new FileReader(name)).readLine() until null; IOException must be handled.
Basic Input/Output and Text File Handling: frequently asked questions
Is BufferedReader in the syllabus?
The syllabus names FileReader and FileWriter. BufferedReader is commonly wrapped around FileReader to read whole lines with readLine(); it is the standard way to read text files line by line.
Why does StringTokenizer skip empty tokens like the one in 'a,,b'?
It treats consecutive delimiters as one separator, so no empty token is returned. If empty fields matter, use String.split, which keeps them.
Where is the file created if I give only its name?
In the program's current working directory (usually the project folder in an IDE). Give a full path to create it elsewhere.
Based on: CISCE ISC 2028 Computer Science syllabus (Classes XI and XII); CISCE Regulations for the ISC Examination Year 2028 (Class XI internal examination)