RandomAccessFile のサンプル

Revised: Mar./16th/2002

文字列の追加

次のサンプルは、複数のコマンドライン引数を取ります。最初の引数を入出力ファイルとして、以降の引数をこのファイルの末尾に追加します。

また、最後にファイルポインタを先頭に戻して、全ての文字を読み込んで標準出力に出力しています。

Append.java:

import java.io.*;

class Append {
	public static void main (String[] args) throws IOException {
		// RandomAccessFile のインスタンス化
		RandomAccessFile raf = new RandomAccessFile(args[0], "rw");

		// ファイルの長さの取得
		long len = raf.length();
		// ファイルポインタを末尾にセット
		raf.seek(len);

		// ファイルに書き込み
		for (int i = 1; i < args.length; i++) {
			raf.writeUTF(args[i] + " ");
		}
		raf.writeUTF("\n");

		// ファイルポインタを先頭にセット
		raf.seek(0L);

		try {
			while (true) {
				// 文字の読み込み
				String cha= raf.readUTF();
				// 標準出力へ出力
				System.out.print(cha);
			}
		} catch (EOFException eofe) {
			// ファイル終了で EOFException 発生
			System.out.println();
			System.out.println("ファイル終了 [EOF]");
		}

		// RandomAccessFile ストリームを閉じる
		raf.close();
	}
}
C:\IO>javac Append.java

C:\IO>java Append test.txt MACBETH
MACBETH

C:\IO>java Append test.txt Though Birnam wood be come to Dunsinane,
MACBETH
Though Birnam wood be come to Dunsinane,

ファイル終了 [EOF]

C:\IO>java Append test.txt And thou opposed, being of no woman born,
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,

ファイル終了 [EOF]

C:\IO>java Append test.txt Yet I will try the last.
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,
Yet I will try the last.

ファイル終了 [EOF]

C:\IO>java Append test.txt
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,
Yet I will try the last.


ファイル終了 [EOF]

C:\IO>java Append test.txt ホールデン・コールフィールド!
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,
Yet I will try the last.

ホールデン・コールフィールド!

ファイル終了 [EOF]

C:\IO>java Append test.txt ビリー・ブラウン!
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,
Yet I will try the last.

ホールデン・コールフィールド!
ビリー・ブラウン!

ファイル終了 [EOF]

C:\IO>

読み取り

上で作ったファイルを読み込むだけのサンプルを挙げておきます。

Page.java:

import java.io.*;

class Page {
	public static void main (String[] args) throws IOException {
		// RandomAccessFile のインスタンス化
		RandomAccessFile raf = new RandomAccessFile(args[0], "r");
		try {
			while (true) {
				// 文字の読み込み
				String cha= raf.readUTF();
				// 標準出力へ出力
				System.out.print(cha);
			}
		} catch (EOFException eofe) {
			// ファイル終了で EOFException 発生
			System.out.println();
			System.out.println("ファイル終了 [EOF]");
		}

		// RandomAccessFile ストリームを閉じる
		raf.close();
	}
}
C:\IO>javac Page.java

C:\IO>java Page test.txt
MACBETH
Though Birnam wood be come to Dunsinane,
And thou opposed, being of no woman born,
Yet I will try the last.

ホールデン・コールフィールド!
ビリー・ブラウン!

ファイル終了 [EOF]

C:\IO>


Copyright © 2002 SUGAI, Manabu. All Rights Reserved.