二进制文件读取器byte []到字符串转换出错了?

时间:2012-06-12 08:42:26

标签: java file file-io io

我正在尝试在文件头中显示什么应该是文本(文件的其余部分是二进制)但是当我打印strtemp时我得到了这个:

strTemp: ??????

这是代码。

String fileName = "test.file";

URI logUri = new File(fileName).getAbsoluteFile().toURI();  

BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(logUri))); 

byte[] btemp = new byte[14];
in.read(btemp);

String strtemp = "";

for(int i = 0; i < btemp.length; i+= 2) {
    strtemp += String.valueOf((char)(((btemp[i]&0x00FF)<<8) + (btemp[i+1]&0x00FF)));
}

System.out.println("strTemp: " + strtemp);

如何让strtemp成为文件中的最新内容?并正确显示它?

2 个答案:

答案 0 :(得分:3)

正如您从http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html的构造函数摘要中可以看到的,您可以直接从字节初始化String。

此外,您应该提供源文件中的字符集。

答案 1 :(得分:0)

对于这种需要,您可以使用ByteBuffer和CharBuffer:

    FileChannel channel = new RandomAccessFile("/home/alain/toto.txt", "r").getChannel();
    //Map the 14 first bytes
    ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, 14);
    //Set your charset here
    Charset chars = Charset.forName("ISO-8859-1");
    CharBuffer cbuf = chars.decode(buffer);
    System.out.println("str = " + cbuf.toString());