Leiutra de arquivo binário (caracteres extendidos ASCII)

6 respostas
M

Tenho um arquivo com conteúdo binário para ser lido, escrito por uma aplicação de terceiro em outra linguagem. Esse arquivo tem em seu conteúdo partes que representam caracteres de controle (checksum) de seu conteúdo, para ser verificado pela minha aplicação em JAVA. Todavia, no conteúdo desse arquivo, alguns bytes gravados tem valores binários que excedem a barreira do 127, mas seus valores devem ser respeitados para o cálculo do CheckSum. Estou lendo o arquivo através do método read da classe FileInputSream, mas estou tendo problemas pois quanto tento executar o algorítmo de cálculo do checksum, o valor numérico da tabela ASCII de caracteres extendidos são lidos de forma alterada. Exemplo: O Caracter 128 gravado no arquivo é lido como -57 em um byte[] ou como 199 em uma String. Como posso pegar o número desses caracteres de forma preservada ?

Obrigado!

6 Respostas

E

Leia o arquivo com um FileInputStream (não FileReader), e não converta seu conteúdo para strings. Trate-o como array de bytes.

V

byte numero = 0xFE; //Um número negativo int valor = (int)(numero & 0xFF); //Considerando o bit de sinal como número mesmo.

M

Pessoal, seguinte: O arquivo é gravado por um programa escrito em C e grava muitos caracteres… Dentre eles caracteres extendidos, incluindo o 128.

O meu programa em Java deve ler esse arquivo e fazer calculos com o valor ASCII dos bytes. Dá certo até ler algum caracter extendido. Aí vai o codigo:

public void load() throws IOException {
        File fileDestiny = new File(this.getFullFile());
        if(fileDestiny.exists()){
//            Charset ASCIICharset = Charset.forName("ISO-8859-1"); 
//            CharsetDecoder ASCIIDecoder = ASCIICharset.newDecoder(); 
            FileInputStream fis = new FileInputStream ( fileDestiny  ) ; 
/*            FileChannel fileChannel = fis.getChannel(); 
            long length = (int) fileChannel.size();
            MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length); 
            CharBuffer cb = ASCIIDecoder.decode(mbb);
            String x = cb.toString();
*/            
            long length = fileDestiny.length();
            long initParser = 0;
            byte[] toParser={};
            this.setRecords(new Vector());
            while (initParser<length){
                int toRead = 
                        ((length-initParser)>MAX_VALUE)?
                            MAX_VALUE:
                            (int) (length-initParser);
                byte[] bytes = new byte[toRead];
                int offset = 0;
                int numRead = 0;
                Now.setTime(new Date());
                long lastByteReaded  = Now.getTimeInMillis();
                boolean remaining = false;
                while (offset<bytes.length && 
                        (Now.getTimeInMillis()-lastByteReaded)<15000) {
                    while (offset < bytes.length
                           && (numRead=fis.read(bytes, offset, bytes.length-offset)) >= 0) {
                            //  Vejam ============== 
                            // Aqui está o problema... leio a array de bytes dentro da variável bytes...

                        offset += numRead;
                        Now.setTime(new Date());
                        if (remaining) {
                            logger.log(Level.FINEST,"Remaining. " + (Now.getTimeInMillis()-lastByteReaded)/1000);
                            remaining = false;
                        }
                        lastByteReaded = Now.getTimeInMillis();
                    }
                    if ((offset < bytes.length) && !remaining) {
                        logger.log(Level.FINEST,"Busy. Wait for read new byte."+fileDestiny);
                        remaining = true;
                    }
                    while ((Now.getTimeInMillis()-lastByteReaded)<1000){
                        Now.setTime(new Date());
                    }
                }


                // Ensure all the bytes have been read in
                if (offset < bytes.length) {
                    logger.log(Level.WARNING,"file load error(timeout): Não pude ler arquivo completamente "+fileDestiny.getName());
                    throw new IOException("file load error(timeout): Não pude ler arquivo completamente "+fileDestiny.getName());
                }
//              System.out.println("Readed file "+ fileDestiny);

                int ascvalue = bytes[556];    // Apenas para teste
                System.out.println("Valor de Ç (ASCII 128 gravado no disco) = "+ ascvalue);           // Apenas para teste
                System.out.println("Agora modificado para unsigned = "+ (ascvalue & 0xFF));           // Apenas para teste

                byte[] readedNow
                = bytes;
                
                int parsedNow = 0;
                while (parsedNow<readedNow.length) {
                    int readedPossibleToParser = 
                    (toParser.length+readedNow.length-parsedNow>MAX_VALUE) ?
                        MAX_VALUE - toParser.length - parsedNow :
                        readedNow.length-parsedNow;
                    
                    byte[] parseNow = new byte[toParser.length+readedPossibleToParser];
                    System.arraycopy(toParser, 0, parseNow, 0, toParser.length);
                    System.arraycopy(readedNow, parsedNow, parseNow, toParser.length, readedPossibleToParser);
                    toParser = parser(parseNow);
                    parsedNow += readedPossibleToParser;
                }
                initParser += parsedNow;
            }
            fis.close();
        } else {
            logger.log(Level.WARNING,"file load error: Arquivo inexistente: "+fileDestiny.getName());
            throw new IOException("file load error: Arquivo inexistente: "+fileDestiny.getName());
        }
    }

A saída do System.out :

Valor de Ç (ASCII 128 gravado no disco) = -57
Agora modificado para unsigned = 199

Esse valor 199 deveria ser 128. Não consigo chegar nele…

V

Não entendi. Como vc declarou ascvalue e logo em seguida imprimiu o valor -57?
Aliás, que codigo bagunçado, hein? Já pensou em usar o FileChannel e o ByteBuffer?

E

Rode o programa abaixo, e confira a sua saída (arquivo “teste.bin”) em um editor hexa. O Java escreve e lê os bytes direitinho. Se você conseguir rodar o programa abaixo direitinho, ele não deve mostrar nada na tela, e gerar um arquivo binário “teste.bin” de 256 bytes.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

class LeArquivo {
    public static void main(String[] args) throws IOException {
        byte[] bytes = new byte[256];
        for (int i = 0; i < bytes.length; ++i) {
            bytes[i] = (byte) i;
        }
        OutputStream fos = new FileOutputStream ("teste.bin");
        fos.write (bytes, 0, bytes.length);
        fos.close();
        InputStream fis = new FileInputStream ("teste.bin");
        byte[] readBytes = new byte [(int) new File ("teste.bin").length()];
        fis.read (readBytes);
        fis.close();
        if (readBytes.length != bytes.length) 
            System.out.printf ("Atencao, tamanho do arquivo lido = %d ! %n", readBytes.length);
        for (int i = 0; i < readBytes.length; ++i) {
            if (readBytes[i] != (byte) i) {
                System.out.printf ("Atencao, byte lido = %02X != esperado = %02X %n", 
                    bytes[i] & 0xFF, readBytes[i] & 0xFF);
            }
        }
    }
}

Exemplo da saída em um editor hexa:

0000    00 01 02 03 04 05 06 07  08 09 0A 0B 0C 0D 0E 0F   ................
0010    10 11 12 13 14 15 16 17  18 19 1A 1B 1C 1D 1E 1F   ................
0020    20 21 22 23 24 25 26 27  28 29 2A 2B 2C 2D 2E 2F    !"#$%&'()*+,-./
0030    30 31 32 33 34 35 36 37  38 39 3A 3B 3C 3D 3E 3F   [telefone removido]:;<=>?
0040    40 41 42 43 44 45 46 47  48 49 4A 4B 4C 4D 4E 4F   @ABCDEFGHIJKLMNO
0050    50 51 52 53 54 55 56 57  58 59 5A 5B 5C 5D 5E 5F   PQRSTUVWXYZ[\]^_
0060    60 61 62 63 64 65 66 67  68 69 6A 6B 6C 6D 6E 6F   `abcdefghijklmno
0070    70 71 72 73 74 75 76 77  78 79 7A 7B 7C 7D 7E 7F   pqrstuvwxyz{|}~.
0080    80 81 82 83 84 85 86 87  88 89 8A 8B 8C 8D 8E 8F   ................
0090    90 91 92 93 94 95 96 97  98 99 9A 9B 9C 9D 9E 9F   ................
00A0    A0 A1 A2 A3 A4 A5 A6 A7  A8 A9 AA AB AC AD AE AF   ................
00B0    B0 B1 B2 B3 B4 B5 B6 B7  B8 B9 BA BB BC BD BE BF   ................
00C0    C0 C1 C2 C3 C4 C5 C6 C7  C8 C9 CA CB CC CD CE CF   ................
00D0    D0 D1 D2 D3 D4 D5 D6 D7  D8 D9 DA DB DC DD DE DF   ................
00E0    E0 E1 E2 E3 E4 E5 E6 E7  E8 E9 EA EB EC ED EE EF   ...ã.....éê..í.ï
00F0    F0 F1 F2 F3 F4 F5 F6 F7  F8 F9 FA FB FC FD FE FF   ð..óôõö÷ø..ûüýþ.

Dica: você teve algumas dificuldades com o “Ç”? É que em Windows-1252 (a codificação usada em C por programas Windows, similar à ISO-8859-1) o Ç tem código 128, e em Unicode o código é U+00C7, ou seja, 199.

Acho que foi isso que lhe confundiu - você NUNCA, NUNCA NUNCA NUNCA deve converter bytes em strings e depois voltar, porque você pode ter uma surpresa desagradável.

M

Pessoal, grato pela ajuda de todos. Eu já havia corrigido o problema e nem havia percebido. É o vício de achar que o erro persiste, mas na verdade o bug agora já era na aplicação que gerava o arquivo, quem também cometia o mesmo equívoco na hora de gravar o arquivo.

Grande abraço a todos.

Criado 30 de novembro de 2009
Ultima resposta 26 de dez. de 2009
Respostas 6
Participantes 3