Olá pessoal,
tenho um array de bytes e gostaria de gravar-los em um arquivo e recupera-los depois, gostaria de gravalos como um array de bytes mesmo ou até em forma binaria, mas precisaria do caminho de volta.
Pesquisei muita coisa mas não achei muita coisa, se alguem souber o fio da meada…
Valeu abração.
Olá!
Acho q uma boa forma de fazer isso é transformar seus bytes para a String na forma hexadecimal. Daí na leitura basta destransformar para bytes. Eu tenho uns algoritmos (peguei aqui mesmo no guj em um tutorial sobre criptografia) para passar um array de bytes para String em hexa e o contrário…aí vai:
/**
* Converte o array de bytes em uma representação hexadecimal.
* @param input - O array de bytes a ser convertido.
* @return Uma String com a representação hexa do array
*/
public static String byteArrayToHexString(byte[] b) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < b.length; i++) {
int j = ((int) b[i]) & 0xFF;
buf.append(DIGITOS_HEXA.charAt(j / 16));
buf.append(DIGITOS_HEXA.charAt(j % 16));
}
return buf.toString();
}
/**
* Converte uma String hexa no array de bytes correspondente.
* @param hexa - A String hexa
* @return O vetor de bytes
* @throws IllegalArgumentException - Caso a String não sej auma
* representação haxadecimal válida
*/
public static byte[] hexStringToByteArray(String hexa)
throws IllegalArgumentException {
//verifica se a String possui uma quantidade par de elementos
if (hexa.length() % 2 != 0) {
throw new IllegalArgumentException("String hexa inválida");
}
byte[] b = new byte[hexa.length() / 2];
for (int i = 0; i < hexa.length(); i+=2) {
b[i / 2] = (byte) ((DIGITOS_HEXA.indexOf(hexa.charAt(i)) << 4) |
(DIGITOS_HEXA.indexOf(hexa.charAt(i + 1))));
}
return b;
}
Quanto a leitura e escrita em arquivo eu acredito que você já conhece BufferedReader e BufferedWriter certo?
Espero ter ajudado!
Abração!