Files and reading data
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
May 19, 2025
Scanner-class since the beginning of this course to read user input.Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
if (line.equals("end")) {
break;
}
// add the read line to a list for later
// handling or handle the line immediately
}System.in) as a parameter to the constructor of the Scanner-class.Files tab, which is found in the same place as the Projects tab.Window menu.Files-tab in NetBeans and how to create a new file.file.txt in the root folder (the folder containing the folder src and the file build.xml) of the exercise template using the Files-tab in NetBeans.Hello, world! on the first line of the file.Scanner-class.Scanner-class, we give the path for the file we want to read as a parameter to the constructor of the class.Paths.get command, which is given the file’s name in string format as a parameter: Paths.get("filename.extension").Scanner-object that reads the file has been created, the file can be read using a while-loop.try, and another to catch potential errors.// first
import java.util.Scanner;
import java.nio.file.Paths;
// in the program:
// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {
// we read the file until all lines have been read
while (scanner.hasNextLine()) {
// we read one line
String row = scanner.nextLine();
// we print the line that we read
System.out.println(row);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}new Scanner(Paths.get("file.txt")) is called), i.e., the folder that contains the folder src and the file build.xml (and possibly other files as well).Files-tab in NetBeans.try {} catch (Exception e) {} block structure to handle exceptions.try starts a block containing the code which might throw an exception.catch defines what happens if an exception is thrown in the try block.catch is followed by the type of the exception handled by that block, for example “all exceptions” catch (Exception e).try {
// code which possibly throws an exception
} catch (Exception e) {
// code block executed if an exception is thrown
}catch, because causing an exception is referred to as throwing an exception.try-catch block.Write a program that prints the contents of a file called “data.txt”, such that each line of the file is printed on its own line.
If the file content looks like so:
Which file should have its contents printed?
(user input) song.txt
I code in the morning, with coffee by my side,
Semicolons dancing, in a class I can't hide.
Compile my dreams, run my soul, Java keeps me whole!
Bugs come at midnight, but I fix them with pride.
From SeoulTech to sunrise, let the logic be my guide.ArrayList<String> lines = new ArrayList<>();
// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.txt"))) {
// we read all the lines of the file
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// we print the total number of lines
System.out.println("Total lines: " + lines.size());ArrayList.Name of the file:
(user input) guestList.txt
Enter names, an empty line quits.
(user input) Chuck Norris
The name is not on the list.
(user input) Jack Baluer
The name is not on the list.
(user input) Kim Yuna
The name is on the list.
(user input) Elon Musk
The name is on the list.
(user input) IU
The name is on the list.
Thank you!continue and the isEmpty-method of the string.// we create a scanner for reading the file
try (Scanner scanner = new Scanner(Paths.get("file.csv"))) {
// we read all the lines of the file
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// if the line is blank we do nothing
if (line.isEmpty()) {
continue;
}
// do something with the data
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}records.csv would look like this :try (Scanner scanner = new Scanner(Paths.get("records.csv"))) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
String name = parts[0];
int age = Integer.valueOf(parts[1]);
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}Name of the file:
(user input) data.txt
lily, age: 3 years
anton, age: 5 years
levi, age: 4 years
amy, age: 1 yearPerson defined in our previous lecture, describing a person (see the next tab).Person type object, after which we add persons to it.Person objects are printed one by one.ArrayList<Person> persons = new ArrayList<>();
// a person object can be created first
Person john = new Person("John");
// and then added to the list
persons.add(john);
// person objects can also be created "in the same sentence"
// that they are added to the list
persons.add(new Person("Matthew"));
persons.add(new Person("Martin"));
for (Person person: persons) {
System.out.println(person);
}public class Person {
private String name;
private int age;
private int weight;
private int height;
public Person(String name) {
this.name = name;
this.age = 0;
this.weight = 0;
this.height = 0;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void growOlder() {
this.age = this.age + 1;
}
public void setHeight(int newHeight) {
this.height = newHeight;
}
public void setWeight(int newWeight) {
this.weight = newWeight;
}
public double bodyMassIndex() {
double heightDivByHundred = this.height / 100.0;
return this.weight / (heightDivByHundred * heightDivByHundred);
}
@Override
public String toString() {
return this.name + ", age " + this.age + " years";
}
}Person, as well as the data from before.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));
}
}
System.out.println("Total amount of people read: " + people.size());Person class, and the class StoringRecords has a body for the method public static ArrayList<Person> readRecordsFromFile(String file).readRecordsFromFile method such that it reads the persons from the file passed as a parameter, and finally returns them in the list returned by the method.main method that you can use to test how your program works.import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class StoringRecords {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Filename:");
String file = scan.nextLine();
ArrayList<Person> records = readRecordsFromFile(file);
System.out.println("Persons: " + records.size());
System.out.println("Persons:");
for (Person person : records) {
System.out.println(person);
}
}
public static ArrayList<Person> readRecordsFromFile(String file) {
ArrayList<Person> persons = new ArrayList<>();
// Write here the code for reading from file
// and printing the read records
return persons;
}
}ArrayList<Team> and extract the team information from each match record on the file.
Computer Language