CS102 · Annotated SlidesFiles — Files
Files · Annotated slides

Files

Reading files with Scanner, writing with FileWriter/PrintWriter, and splitting lines with String.split.

Slide text Study notes Highlight: key words Tips, tricks & traps Seen again elsewhere How it can come up

Files Revision

CS102
1
Exam weight Low
  1. Remember Integer.parseInt(string) to turn text fields into numbers.

•Read from a file in java using Scanner class •Write to a file in Java using the FileWriter class or PrintWriter class •Process a String line in a file using the method split.

2
Exam weight Low

    FileWriter Class

    • The class is used for writing streams of characters.
    • This class has several constructors to create required objects.
    • Some of the constructors and their description:
      • FileWriter(File file) This constructor creates a FileWriter object given a File object.
      • FileWriter(File file, boolean append) This constructor creates a FileWriter object given a File object with a boolean indicating whether or not to append the data written.
    3
    Exam weight Medium
    1. FileWriter writes characters; new FileWriter(name, true) APPENDS instead of overwriting.
    🎯 How this can come up · 1 question
    MCQ

    new FileWriter("data.txt", true) will:

    Code Examples

    • Write Example
    • Revision from CS101 lectures Ch12 (WriteData)
    • Read Example
    • Revision from CS101 lectures Ch12 (ReadData)
    4
    Exam weight Low

      Split Method

      • This method splits the string around matches of the given regular expression.
      • public String[] split(String regex)
      5
      Exam weight High
      1. split(regex) returns a String[] of the pieces: "a,b,c".split(",") → ["a", "b", "c"].
      🎯 How this can come up · 1 question
      MCQ

      "Ali:20:A".split(":") returns an array of length:

      Split Coding Example

      • Write a program that read from a file "student.txt" line by line and split the lines according to: then it should display them to the screen. In addition it should count the number of students and writes it to a file "Output1.txt".
      6
      Exam weight Low
      1. Read a line, split it, parse the numeric fields, display.