金子邦彦研究室プログラミングJava のプログラム例バイナリファイル入力(Java を使用)

バイナリファイル入力(Java を使用)

【サイト内の Java 関連の資料】

サンプルプログラム:Main.java

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static String IN_FILE_NAME = "1.png";
    public static void main(String[] args) {

        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream( IN_FILE_NAME ) );
            int b;
            int bytes = 0;
            // 1バイト単位で読み込み
            while ((b = in.read()) != -1) {
                // %2e は2桁の16進数
                if ( ( bytes % 16 ) == 0 ) System.out.printf( "%1$8x : ", bytes );
                System.out.printf("%1$2x ", b);
                if ( ( bytes % 16 ) == 15 ) System.out.println( " " );
                bytes++;
            }
            System.out.println( "\n " + bytes + " bytes" );
        } catch (FileNotFoundException e) {
            System.out.println( "File Not Found" );
        } catch (IOException e) {
            System.out.println( "I/O Exception" );
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            }
        }
    }
}

【Windows での実行】

Windows で,ファイル Main.java を編集し実行するために,次のコマンドを, コマンドプロンプトで実行する.

cd %LOCALAPPDATA%
notepad Main.java
javac -encoding UTF-8 Main.java
curl -O https://www.kkaneko.jp/sample/face/1.png
java Main

[image]