2016-05-15 161 views
1

ORD PHP我想编辑一个PHP的代码使用ORD方法,将PHP代码如下:的Java:方法与Java

$fh=fopen("../ip.data","r"); 
fseek($fh,327680); 
$country_id=ord(fread($fh,1)); //return 137 

我试图用Java编写代码:

FileReader ip=new FileReader("ip.data"); 
int i = 0; 
int str; 
while((str=ip.read()) != -1){ 
    if(i==327681){ 
     System.out.println(str); //return 0 
     break; 
    } 
i++; 
} 

但是两者并不相同。 我知道PHP中的ord('a')==97,Java中的(int)'a'==97。 ip.data下载here

+0

请发布和示例'ip.data'文件和你有什么区别你在Java和PHP –

回答

1

FileReader假定系统的默认字符集为输入文件,该文件可能是UTF-8例如*在这种情况下,多达四个字节将被读为“形成了”单字符你的FileReader得到。读()。
所以,也许(只是猜测在这一点上),这是问题。你的php代码不会假设任何编码,它只是读取一个(8位)字节,而它在java中的等价物就是

fis = new FileInputStream("ip.data"); 
country_id = fis.read(); // FileInputStream.read() is reading a byte, not a character 

*)为了检验这一假设,试图

FileReader fr = new FileReader("ip.data") 
System.out.println(fr.getEncoding()); 

是什么打印?

+0

谢谢你的答案。 – zhanzezhu

-1

试试这个:

String str = "t"; 
byte b = str.getBytes()[0]; 
int ascii = (int) b; 

也许你不得不使用字符。