您不应该使用fileData.toString().indexOf()
,因为您正在使用二进制数据。您必须搜索一系列字节。
以下函数检索指定模式的位置:
public function indexOf(bytes:ByteArray, search:String, startOffset:uint = 0):void
{
if (bytes == null || bytes.length == 0) {
throw new ArgumentError("bytes parameter should not be null or empty");
}
if (search == null || search.length == 0) {
throw new ArgumentError("search parameter should not be null or empty");
}
// Fast return is the search pattern length is shorter than the bytes one
if (bytes.length < startOffset + search.length) {
return -1;
}
// Create the pattern
var pattern:ByteArray = new ByteArray();
pattern.writeUTFBytes(search);
// Initialize loop variables
var end:Boolean;
var found:Boolean;
var i:uint = startOffset;
var j:uint = 0;
var p:uint = pattern.length;
var n:uint = bytes.length - p;
// Repeat util end
do {
// Compare the current byte with the first one of the pattern
if (bytes[i] == pattern[0]) {
found = true;
j = p;
// Loop through every byte of the pattern
while (--j) {
if (bytes[i + j] != pattern[j]) {
found = false;
break;
}
}
// Return the pattern position
if (found) {
return i;
}
}
// Check if end is reach
end = (++i > n);
} while (!end);
// Pattern not found
return -1;
}
然后你可以这样使用这个函数:
var extractedBytes = new ByteArray();
var startPos:int = indexOf(fileData, "<<<start>>>");
var endPos:int;
if (startPos == -1) {
trace("<<<start>>> not found");
} else {
endPos = indexOf(fileData, "<<<end>>>", startPos + 11); // "<<<start>>>".length = 11
}
if (startPos == -1) {
trace("<<<end>>> not found");
} else {
// Extract the bytes between <<<start>>> and <<<end>>>
fileData.readBytes(extractedBytes, startPos + 11, endPos);
}
免责声明:我没有测试我的代码!