Skip to content

Activity 9: File/Input Output

Instructions

Example Code

Model 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;

public class ScannerDemo {

    public static void main(String[] args) {

        System.out.println("==== Example 1 ====");
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String line = in.nextLine();
            System.out.println(line);
        }

        System.out.println("==== Example 2 ====");
        String text = "1 fish 2 fish red fish blue fish";
        Scanner sc = new Scanner(text);
        System.out.println(sc.nextInt());
        System.out.println(sc.next());
        System.out.println(sc.nextInt());
        System.out.println(sc.next());

    }

}

Model 2

Download title2020.tsv and put in the src/ folder with IMDb.java.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.io.File;
import java.util.Scanner;

public class IMDb {

    public static void main(String[] args) {
        File file = new File("src/title2020.tsv");
        Scanner in = new Scanner(file);
        in.useDelimiter("\t");  // tab separated values
        for (int i = 0; i < 3; i++) {
            String line = in.nextLine();
            System.out.println(line);
        }
        in.close();
    }

}

Question 11

int count = 0;
while (count < 1) {
    String tid = in.next();
    String type = in.next();
    String title = in.next();
    if (tid.equals("6723592")) {
        System.out.println(tid + " is a " + type + " named " + title);
        count++;
    }
    in.nextLine();
}