php inputstream,PHP实现java中的DatainputStream类.

在项目中,碰到一个解析流的操作,php里面没有现成的类.

那没办法,只能用二进制模式打开文件,再和java的datainputstream对比着打开文件,一个一个的实现流读取和解析.

废话不多说,代码贴出,其实很简单很简单.

DataInputStream.php<?php

/**

* 流解析

* ---------------------------------------------

* @Author: Simon 夏向红 sanwkj@163.com

* @Date: 2012-02-22

* @package cn.com.nearme.gostore.theme

* @name :DataInputStream.php

* @version v1.0

*

*/

class DataInputStream {

private $stream = null;

/**

* 构造函数

*

* @param stream of fopen .. $in

*/

public function __construct( $in ){

$this->stream = $in;

}

/**

* 析构函数

*

*/

public function __destruct(){

@fclose( $this->stream );

}

/**

* 读取字节

*

* @param int sizeof you want to read $len

* @return string

*/

private function read( $len=1 ){

$len = intval( $len );

if( $len>0 ) {

if( !feof( $this->stream ) ) {

$read = @fread($this->stream,$len);

if( strlen($read)!=$len ){

throw new Exception('流文件已经到末尾,读取错误',222);

} else {

return $read;

}

} else {

throw new Exception('流文件已经到末尾,读取错误',222);

}

} else {

return '';

}

}

/**

* 读取一个字节,并转换成int

*

* @return int

*/

public function readByte(){

return hexdec(bin2hex($this->read(1)));

}

/**

* 短整形

*

* @return int

*/

public function readShort(){

return hexdec(bin2hex($this->read(2)));

}

/**

* 整形数据

*

* @return int

*/

public function readInt(){

return hexdec(bin2hex($this->read(4)));

}

/**

* 读取一个字符串

*

* @return string

*/

public function readUTF(){

$len = $this->readShort();

return $this->read($len);

}

/**

* 读取指定长度的数据,并作为字符串返回,图片等二进制文件,可能需要这样读取.

*

* @param int $len

* @return unknown

*/

public function readFully( $len ) {

return $this->read( $len );

}

/**

* readUTF的别名

*

* @return unknown

*/

public function readString(){

return $this->readUTF();

}

/**

* 长整形.

*

* @return unknown

*/

public function readLong(){

return hexdec(bin2hex($this->read(8)));

}

}

?>

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值