Javaがバイナリファイルストリームを処理の方法
Javaでは、バイナリファイルストリームはInputStreamとOutputStreamを使用して処理できます。
FileInputStreamとBufferedInputStreamを使用して入力ストリームを作成することでバイナリファイルを読み取ることができます。例えば、
try (FileInputStream fis = new FileInputStream("file.bin");
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = bis.read(buffer, 0, bufferSize)) != -1) {
// 处理读取的二进制数据
}
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream と BufferedOutputStream を用いて出力ストリームを作成すればバイナリファイルへの書き込みが可能。例:
try (FileOutputStream fos = new FileOutputStream("file.bin");
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] data = // 要写入的二进制数据
bos.write(data);
bos.flush();
} catch (IOException e) {
e.printStackTrace();
}
バイナリーファイルストリームを処理する際には、read() メソッドを使用してデータを 1 バイトずつ読み取る方法や、read(byte[] buffer) メソッドを使用して一定長のデータブロックを読み取る方法など、さまざまな手法を使用できます。
また、バイナリーファイルの処理後は、関連する入力ストリームと出力ストリームを適切に閉じる必要があります。上記のサンプルでは、try-with-resources ステートメントを使用してストリームを自動的に閉じます。