0

ファイルヘッダーにテキストであるはずの内容を表示しようとしています(ファイルの残りの部分はバイナリです)が、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をファイルの内容にするにはどうすればよいですか?そしてそれを正しく表示するには?

4

2 に答える 2

3

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.htmlのコンストラクタの概要からわかるように、バイトから直接文字列を初期化できます。

また、ソースファイルにある文字セットを指定する必要があります。

于 2012-06-12T08:49:39.343 に答える
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());
于 2012-06-12T09:01:23.137 に答える