Table of contents:

  1. Reading from keyboard
  2. Reading from a file
  3. Reading data of a specific format from a file
  4. Reading Objects From a File

Reading from keyboard

Application that runs on the Internet such as WhatApp, Messanger, Facebook, WhatsApp, and Telegram, handle user information that is stored in file-based databases. What these all have in common is that they read and manipulate data in one way or another. Also, the data being handled is ultimately stored in some format in one or more files.

In this example, we pass system input System.in as a parameter ti the constructor of the Scanner class. The input if the user is directed into the input stream one line at a time, which means that the information is send to be handled every time the user enters a new line.

Example:

Scanner scanner = new Scanner(System.in);

while (true) {
    String line = scanner.nextLine();

    if (line.equals("end")) {
        break;
    }
}

Reading from a file

Example:

try (Scanner scanner = new Scanner(Paths.get("example_file.txt"))) {

    while (scanner.hasNextLine()) {
        String row = scanner.nextLine();
        System.out.println(row);
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

File is read from the project root by deafault, when new Scanned(Path.get("example_file.txt")) is called. Folder that contains the folder src and the filepom.xml.

Read all the lines in the file, example:

try (Scanner scanner = new Scanner(Paths.get("example_file.txt"))) {

    while (scanner.hasNextLine()) {
        lines.add(scanner.nextLine());
    }
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

Reading data of a specific format from a file

Data is often stored in files using a specific format. One such format that’s already familiar to us is comma-separated values (CSV) format, i.e., data separated by commas.

Example:

while (true) {
    System.out.print("Enter name and age separated by a comma: ");
    String line = scanner.nextLine();

    if (line.equals("")) {
        break;
    }

    String[] parts = line.split(",");
    String name = parts[0];
    int age = Integer.valueOf(parts[1]);

Reading Objects From a File

Example:

ArrayList<Person> people = new ArrayList<>();

try (Scanner scanner = new Scanner(Paths.get("records.txt"))) {

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        String[] parts = line.split(",");
        String name = parts[0];
        int age = Integer.valueOf(parts[1]);

        people.add(new Person(name, age));
    }
}

Reading objects from a file is a clear responsibility in and of itself, and should for that reason be isolated into a method.


Reference:

  1. Class FileReader

My site is free of ads and trackers. Was this post helpful to you? Why not BuyMeACoffee