Programmatically Edit a .webarchive File

493 Views Asked by At

I'm building an AIR app using Actionscript and I want to programmatically insert a piece of text into a .webarchive file. The problem is that every time I insert the text, the file somehow gets corrupted. The code I'm using looks like this:

var stream:FileStream = new FileStream();                       
stream.open(file, FileMode.READ);   
var body:ByteArray = new ByteArray();                       
stream.readBytes(body, file.size);                      
var result:Array = pattern.exec(body.toString());                   
var new_body:String;                        
new_body = body.toString().replace(pattern, "replacing text here!</body>"); 
stream.close();                     
stream.open(file, FileMode.WRITE);                      
stream.writeUTFBytes(new_body);                     
stream.close();

I'm guessing the problem has to do with the encoding of the .webarchive file. Does anyone have any ideas on how to fix this? Thanks in advance!

1

There are 1 best solutions below

0
On

You should always use stream.readUTFBytes() or stream.readUTF() when reading text information from files. I'm guessing some actual encoding issues arise when you convert bytes to string in your code. The correct code would be:

var stream:FileStream = new FileStream();                       
stream.open(file, FileMode.READ);   
var body:String = stream.readUTFBytes(stream.bytesAvailable);   
stream.close();               
var new_body:String = body.replace(pattern, "replacing text here!</body>");  
stream.open(file, FileMode.WRITE);                      
stream.writeUTFBytes(new_body);                     
stream.close();