Substitute for Files.readAllBytes and .toPath () for Android

0

I have the following lines in my app in a class that acts as AsyncTask to include an image in the body of a query HTTP .

I have the following object File :

val file = File(getContext().cacheDir, "fileName")
file.createNewFile()

and then with a FileOutputStream I write a BitMap in that file in such a way:

val fos = FileOutputStream(file)
fos.write(bitMapData)
fos.flush()
fos.close()

And finally, to write all the bytes in the request of the query, I use:

val bytes = Files.readAllBytes(file.toPath())
request.write(bytes) //La variable request es el OutputStream del objeto HttpUrlConnection

These two functions, readAllBytes() and toPath() ask me for a minimum API of 26, which is very high, which would be your substitute for smaller APIs.

    
asked by Ibrahim Hernández Jorge 21.04.2018 в 16:33
source

1 answer

1

How well you comment Files.readAllBytes () was added from API 26.

You can configure your project with:

compileSdkVersion=26 and targetSdkVersion=26

If you want a code for previous APIs:

File file = new File("<ruta de archivo>");

     byte[] b = new byte[(int) file.length()];
     try {
           FileInputStream fileInputStream = new FileInputStream(file);
           fileInputStream.read(b);
           for (int i = 0; i < b.length; i++) {
                       System.out.print((char)b[i]);
            }
      } catch (FileNotFoundException e) {
                  System.out.println("No existe archivo en ruta especificada.");
                  e.printStackTrace();
      }
      catch (IOException ioe) {
               System.out.println("Error Reading The File.");
                ioe.printStackTrace();
      }
    
answered by 21.04.2018 / 18:33
source