Change CRT file to byte

7

I need to convert a file .crt to byte so I can send it by socket. This code works in Java, but how would I write it on Android?

Path path = Paths.get("sdcard/certificado.crt");
byte[] certificado = Files.readAllBytes(path);
    
asked by anonymous 16.03.2014 / 13:06

3 answers

0

Sorry for the delay, I managed to do it some time ago so I forgot to post my answer here. My code stayed like this

    File f = new File(cert); // o cert é o caminho do meu certificado ex: sdcar/download/certificado.crt
    FileInputStream input = new FileInputStream(f);
    byte[] certificado = new byte[(int) f.length()];
    input.read(certificado);
    
03.04.2014 / 22:16
2

Untested code

With my searches I got the following:

public static byte[] convertFileToByteArray(File f)
{
    byte[] byteArray = null;
    try
    {
        InputStream inputStream = new FileInputStream(f);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024*8];
        int bytesRead =0;

        while ((bytesRead = inputStream.read(b)) != -1)
        {
            bos.write(b, 0, bytesRead);
        }
        byteArray = bos.toByteArray();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return byteArray;
}

Source: link

But I also found these:

link link

And the one I believe is not quite what you want, but it's useful:

>     
18.03.2014 / 00:45
2

Well, you can use the Apache Commons library to achieve this. Note the functions IOUtils.toByteArray(InputStream input) and FileUtils.readFileToByteArray(File file) .

If you do not choose to use what was suggested above you can use this function below.

public static byte[] getFileBytes(File file) throws IOException {
    ByteArrayOutputStream ous = null;
    InputStream ios = null;
    try {
        byte[] buffer = new byte[4096];
        ous = new ByteArrayOutputStream();
        ios = new FileInputStream(file);
        int read = 0;
        while ((read = ios.read(buffer)) != -1)
            ous.write(buffer, 0, read);
    } finally {
        try {
            if (ous != null)
                ous.close();
        } catch (IOException e) {
            //
        }
        try {
            if (ios != null)
                ios.close();
        } catch (IOException e) {
            // 
        }
    }
    return ous.toByteArray();
}

Code found in this answer

    
18.03.2014 / 01:40