入出力・ファイル操作 - file handling(Java 第9回)

はじめに

第9回は入出力・ファイル操作である。
今までとは毛色が違うので、頭を切り替える必要がある。

入出力・ファイル操作の解説

今回は具体例を先に出してから、個々を解説する。
具体例1(テキストファイルを全行表示)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadAllLines {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

まず、mainメソッドの前にファイル操作に必要なクラスをimportしている。
mainメソッド内では、file.txtをFileReader(ファイルから文字を読み込む)で読み込んだオブジェクトをBufferReaderでwrapしてBufferingする。こうすると、readLineメソッド(1行ずつ表示)で効率的に文字ファイルを読み込めるという流れである。

具体例2(コンソールで入力して、入力内容を表示)

import java.util.Scanner;

public class UserInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in); // Create a Scanner object

        System.out.println("Please enter your name: ");
        String name = scanner.nextLine(); // Read a line of text

        System.out.println("Please enter your age: ");
        int age = scanner.nextInt(); // Read an integer

        System.out.println("Hello, " + name + ". You are " + age + " years old.");

        scanner.close(); // Always close the scanner when you're done with it
    }
}

Scannerクラスをimportする。nextLine()やnextInt()が使えるので、コンソールでデータを入力できる。

まとめ

ファイル操作に関する処理はもっとたくさんありますが、雰囲気をつかむことが目的なので、ここらへんでやめときます。

注意

このページは大学のJavaの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。