Change CRT file to byte

Asked

Viewed 232 times

7

I need to convert a file .crt byte to be able to send 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);

3 answers

2

Untested code

With my search I obtained 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: http://androidsnippets.wordpress.com/2012/08/07/how-to-convert-a-file-to-byte-array/

But I also found these:

https://stackoverflow.com/questions/14466469/convert-android-graphics-path-object-to-byte-and-back https://stackoverflow.com/questions/13466908/create-a-arraylist-of-byte-array-in-android

And the one I believe isn’t quite what you want, but it’s useful:

http://examples.javacodegeeks.com/core-java/io/fileoutputstream/write-byte-array-to-file-with-fileoutputstream/

2

Well, you can use the library Apache Commons to achieve this. Attention to 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

0


Sorry personal delay I managed to do a while ago only I forgot to post here my answer. My code was 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.