0

I'm trying to display whats in the file header which should be text (the rest of the file is binary) but when I print strtemp I get this:

strTemp: ??????

Here is the code.

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);

How do I get strtemp to be whats in the file? and to display it properly?

3
  • 2
    Have you tried new String(btemp) instead of your loop? Commented Jun 12, 2012 at 8:45
  • 1
    What's in the file? characters? In which character encoding? How were they written? Commented Jun 12, 2012 at 8:48
  • why switch HIGH byte and LOW byte, is it multibyte character? is it little-endian? what's the charset encoding? Commented Jun 12, 2012 at 8:52

2 Answers 2

3

As you can see from the Constructor summary of http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html you can initialize a String from bytes directly.

Also you should supply the charset you have in your source file.

Sign up to request clarification or add additional context in comments.

Comments

0

For this kind of need you can use ByteBuffer and 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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.