Napisałem kod do odczytu plików w trybie binarnym, testuję go na pliku bmp o wymiarach 2px2px(1 - kolor biały, 0 kolor czarny)*
Obrazek ma taki rozkład kolorów:
0 1
1 0
Kod źródłowy:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BinaryInputFile {
private File file;
private byte[] bin;
public BinaryInputFile(String pathname) {
file = new File(pathname);
}
public void getFile() {
try {
FileInputStream fpIn = new FileInputStream(file);
DataInputStream fp = new DataInputStream(fpIn);
int counter = 0;
while(true) {
try {
System.out.print(fp.readByte() + " ");
counter++;
} catch(IOException ex) {
System.err.println("Drukowanie: " + ex);
try {
fp.close();
} catch(IOException exc) {
System.err.println(exc);
}
break;
}
}
} catch(FileNotFoundException ex) {
System.err.println(ex);
}
}
}
W wyniku otrzymuję:
66 77 70 0 0 0 0 0 0 0 54 0 0 0 40 0 0 0 2 0 0 0 2 0 0 0 1 0 24 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 -1 0 0 0 0 0 0 0 0 -1 -1 -1 0 0 Drukowanie: java.io.EOFException
I teraz mam pytania:
- Czy w dobry sposób odczytuję bity z pliku?
- Co oznaczają liczby większe od 1, a co oznacza wartość 0 oraz -1
EDIT:
Zmieniłem kod na taki:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class BinaryInputFile {
private File file;
private byte[] bin;
public BinaryInputFile(String pathname) {
file = new File(pathname);
}
public void getFile() {
try {
RandomAccessFile fp = new RandomAccessFile("D:/a.bmp", "r");
long pointer = 0;
int counter = 0;
try {
fp.seek(0);
while(pointer < fp.length()) {
System.out.print(fp.readUnsignedByte() + " ");
pointer = fp.getFilePointer();
counter++;
}
fp.close();
System.out.println("\n" + counter);
} catch(IOException exc) {
System.err.println("IOException: " + exc);
}
} catch(FileNotFoundException ex) {
System.err.println("Plik nieodnaleziony");
}
}
}
Wynik jaki otrzymuję:
66 77 70 0 0 0 0 0 0 0 54 0 0 0 40 0 0 0 2 0 0 0 2 0 0 0 1 0 24 0 0 0 0 0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 255 255 0 0 0 0 0 0 0 0 255 255 255 0 0
Od liczby 255 zaczyna się malowanie obrazka, cała reszta przed pierwszą wartością 255 to nagłówki. Nasuwa mi się pytanie czy nagłówki zawsze wynoszą 54 bajty?