Stream
まずは、シンプルな File I/O の例を紹介します。(kobeU.cs.samplesIO.UseSimpleIO)
- 入力ファイルと出力ファイルをオープンし、
- 4KB 単位で入力ファイルを読み込んでは、出力ファイルに書き出す
だけのプログラムです。
try-catch については、次の例外で説明します。
private static void copyfile(String from, String to)
throws IOException {
/* FileInputStream作成, FileNotFoundException の可能性 */
InputStream in = new FileInputStream(from);
/* FileOutputStream作成, FileNotFoundException の可能性 */
OutputStream out = new FileOutputStream(to);
byte[] buf = new byte[BUFSIZE];
try {
while (true) {
/* in から read。IOException の可能性 */
int size = in.read(buf, 0, BUFSIZE);
if (size < 0) { /* EOF なら、loop を抜けて */
break;
} else {
/* size 分, out に出力。IOException の可能性 */
out.write(buf, 0, size);
}
}
} finally {
in.close();
out.close();
}
}
使っているのは、
- java.io.FileInputStream: java.io.InputStream の一種
- read() を利用
- java.io.FileOutputStream: java.io.OutputStream の一種
- write(), close() を利用
です。
今回は、「ファイル名」を指定して、InputStream, OutputStream を作成しました。 ただ、コンストラクタ情報を見てもらえば分かるように、java.io.File オブジェクトを元に生成することも可能です。
注
:
- プログラムでは、入力データには
src/main/resources/samplesIO/sample.in
を用いています。- 以前、英語版wikipediaから、阪急六甲中心に大学の緯度経度情報を取得してまとめたものです。
- 一方で、出力ファイルは
プロジェクト直下
に作成されるようにしています。このプログラムではsampleOut.txt
というファイルが作成されます。ただ、新規ファイルが追加されても Eclipse などの処理系は気が付かないので、プロジェクト directory を右クリックして、リフレッシュ
操作をしてください。