Reputation: 1020
I'm trying to figure out how to replace binary data using Java. below is a PHP example of replacing "foo" to "bar" from a swf file.
<?php
$fp = fopen("binary.swf","rb");
$size = filesize("binary.swf");
$search = bin2hex("foo");
$replace = bin2hex("bar");
$data = fread($fp, $size);
$data16 = bin2hex($data);
$data16 = str_replace($search, $replace, $data16);
$data = pack('H*',$data16);
header("Content-Type:application/x-shockwave-flash");
echo $data;
?>
How do I do this in Java.
Upvotes: 2
Views: 1192
Reputation: 109413
Try this:
InputStream in = new FileInputStream("filename");
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
sb.append(new String(b, 0, n));
}
in.close();
String data = sb.toString();
data = data.replace("foo", "bar");
//do whatever you want with data
I'm not sure how well this will work with truly binary data (such as a SWF file as used in your example). It's possible that binary data will be interpreted as Unicode characters, and will appear differently if you print them. It's also possible that it will throw some kind of exception for invalid character encodings. You probably want to use a ByteArrayInputStream for binary data, but then you don't have easy ways of doing a search/replace.
Upvotes: 1