问题
public static void main(String[] args) {
File inFile = null;
if (0 < args.length) {
inFile = new File(args[0]);
}
BufferedInputStream bStream = null;
try {
int read;
bStream = new BufferedInputStream(new FileInputStream(inFile));
while ((read = bStream.read()) > 0) {
getMarker(read, bStream);
System.out.println(read);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (bStream != null)bStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void getMarker(int read, BufferedInputStream bStream) {
}
I want to find the long 1234567890 in the bufferedInputStream. Am I able to search the bufferedInputStream for a long type? (I'm not sure whether I need 'read' as a parameter. I doubt it, I may remove that). How do I search a bufferedInputStream? Big endian, 8 byte aligned.
The initial marker that I'm searching for contains the value 1234567890. Once I have found that value I want to put the value of 2 bytes into a variable. These 2 bytes are located 11 bytes after marker.
回答1:
With the method java.io.DataInputStream.readLong() it's possible to read data 8 bytes per 8 bytes. But the question is: the file contains only long or other data?
If the data may be anywhere, we have to read 8 times the file beginning at the offset 0, 1, 2 and so on.
class FuzzyReaderHelper {
public static final long MAGIC_NUMBER = 1234567890L;
public static DataInputStream getStream( File source ) {
boolean magicNumberFound = false;
for( int offset = 0; !magicNumberFound && offset < 8; ++offset ) {
dis = new DataInputStream( new FileInputStream( source ));
for( int i = 0; i < offset; ++i ) {
dis.read();
}
try {
long l;
while(( l = dis.readLong()) != MAGIC_NUMBER ) {
/* Nothing to do... */
}
magicNumberFound = true;
for( int i = 0; i < 11; ++i ) {
dis.read();
}
return dis;
}
catch( EOFException eof ){}
dis.close();
}
// choose:
throw new IllegalStateException( "Incompatible file: " + source );
// or
return null;
}
}
The next steps are up to you:
DataInputStream dis = FuzzyReaderHelper.getStream( new File( root, "toto.dat" ));
if( dis != null ) {
byte[] bytes = new byte[2];
bytes[0] = dis.read();
bytes[1] = dis.read();
...
}
来源:https://stackoverflow.com/questions/16902402/java-search-for-a-long-in-a-binary-file-input-8-byte-aligned-big-endian