アットウィキロゴ

バイナリの読み書き(1)

7
★バイナリの読み書き
■バイナリファイルの読み込み手順
①ファイルを開く
FileStream(ストリームクラス)のオブジェクトを生成してファイルを読み込む
FileInputStream in = new FileInputStream (“file3.dat”); ←ファイル生成
②データを読み込む
readメソッドを使用する。読み込んだ1バイトデータをint型で返す。
読み込むデータがなくなるとー1を返す。
Int c;
c = in.read();
③ファイルを閉じる
close()メソッドを使用
in.close();
■バイナリファイルの書き出し手順
①ファイルを開く
FileOutputStream(ストリームクラス)のオブジェクトを生成してファイルを書き出す
FileOutputStream out = new FileOutputStream (“file4.dat”);  ←この名前でファイル生成
②データを書き出す
write()メソッドを使用する。引数として与えたデータをファイルに書き出す。
引数にはint型かbyte型の値を指定
out.write(65);
③ファイルを閉じる
close()メソッドを使用
out.close();
 
■文字ストリームへの変換
InputStreamReader
バイナリ入力→文字入力へ変換
バイナリデータを読み込むオブジェクトを引数として受け取る
FileInputStream ifile = new FileInputStream(“file5.dat”);
InputStreamReader in = new InputStreamReader(ifile);
                 ↑オブジェクト名   ↑InputStreamReaderクラスのオブジェクト
 
OutputStreamReader
バイナリ出力→文字出力へ変換
バイナリデータを読み込むオブジェクトを引数として受け取る
FileOutputStream ofile = new FileOutputStream(“file5.dat”);
OnputStreamReader out = new OutputStreamReader(ofile);
                 ↑オブジェクト名   ↑OutputStreamReaderクラスのオブジェクト
 
 
    サンプルプログラム
 
 
import java.io.*;
 
class InOut {
   public static void main(String[] args) {
      try {
          String filename = "file.dat";
          FileOutputStream out = new FileOutputStream(filename);
          FileInputStream file = new FileInputStream(filename);
           InputStreamReader in = new InputStreamReader(file);
 
           for(byte i = 1; i <= 10; i++) {
              out.write(i);
           }
 
           int c;
           while((c = in.read()) != -1) {
                System.out.print(c + " ");
           }
 
           in.close();
           out.close();
      } catch (IOException e) {
           System.out.println("ファイルがありません。");
      }
   }
}
 
 
最終更新:2008年03月13日 20:59