简体   繁体   中英

Error in writing ascii characters into a file in java/android

I have the following code:

private char[] headerToWrite;
protected String workingFileName;

private void writeHeaderToFile()
{
    try
    {
        String completeFile = new String(headerToWrite);

        File myFile = new File(workingFileName);

        FileOutputStream fOut = new FileOutputStream(myFile);

        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

        myOutWriter.append(completeFile);
        myOutWriter.close();
    }
    catch (IOException ioe) 
    {
        ioe.printStackTrace();
    }
}

In the above code, the variable headerToWrite contains an array, where the first few values are: [1, Q, H, S, , 4, ±, Q, .....] . This in hex is [31, 51, 48, 53, 01, 34, B1, 51...] .

It is used to create a string completeFile which = 1QHS 4±Q...

However, when the file is being written, the file contains 1QHS 4űQ..... which in hex is [31 51 48 53 01 34 c2 b1 51] ....

I couldn't understand why there was an additional c2 but I discovered that the bytes inside myOutWriter were as follows: [49, 81, 72, 83, 1, 52, -62, -79, 81] ....

The interesting point here is the -62, -79 which seems to be responsible for c2, b1 . For it to work, -62, -79 should just be 177 , which is the decimal for b1. Interestingly 177 + 79 is 256.

So evidently, in the transfer from ascii characters in completeFile to bytes in myOutWriter , c2 is being added.

I was wondering if anyone could explain why and how to fix it.

Thanks

it could be because by appending a String, it actually converts it to byte array using default encoding, which is probably UTF-8. To fix this, convert your string into byte array by using ISO 8859-1 encoding and write that byte array to your output stream.

The -79 can be explained by overflow. As byte is a signed char and 177 > 127 (which is the maximal value for a byte), it will overflow and -79 is the result. I can not really explain the -62, but you are clearly using the wrong encoding (probably UTF-8). Try using a different encoding ( ISO 8859-1 might do the trick).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM