テキストファイルの内容を表示する

概要

1.コマンドラインからテキストファイル名を指定する
2.コマンドラインに引数がない場合はプログラム終了
3.指定したファイルが存在しない場合は例外を投げてプログラム終了
4.ファイルが存在する場合は1行ずつ内容を画面に表示する(行番号入り)

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FileLister {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("コマンドライン引数がありません。");
            System.exit(1);
        }
        System.out.println("File name:" + args[0]);
        try {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            for (int i = 0;; i++) {
                String line = reader.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(i + " " + line);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("ファイルが存在しません。" + e);
        } catch (Exception e) {
            System.out.println("例外が発生しました。" + e);
        }
    }

}

実行結果(あらかじめテキストファイル「helloWorld」を作成しておき、コマンドライン引数に指定する)

>java FileLister helloWorld
File name:helloWorld
0 Hello World.
1 I'm fine today.
2 Thank you.
3 Let's take a break.

【早期購入特典あり】Hello,world!/コロニー(期間限定盤)[ジャケットverステッカー付]

【早期購入特典あり】Hello,world!/コロニー(期間限定盤)[ジャケットverステッカー付]