Search code examples
androidarraystype-conversionfilesize

Compare size of file and size of byte array of that file


When we convert the file (say - image) To byteArray how can be approximately compared between them (image file and byteArray) ?

Is there also a way to first convert image file to byteArray and this byteArray has to be written in a text-file.. Again after this read these lines of byteArray from text-file and make byteArray and hence converted to image file...... I'm beginner and just for knowledge purpose i want to know....


Solution

  • You can convert your image to byte array like this.

      BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ImageIO.write(bImage, "jpg", bos );
      byte [] data = bos.toByteArray();
    

    Yes you can directly compare 2 byteArray.

    Just do something like

    if (bytearray1.length == bytearray2.length)
       //its same
    

    Try this to write the ByteArray in text file

    public void writeToFile(byte[] array) 
    { 
       try 
       { 
           String path = "/data/data/YOURFILE.txt"; //provide your path here
           File file = new File(path);
           if (!file.exists()) { //just to check if file is actually present
              file.createNewFile();
           }
           FileOutputStream stream = new FileOutputStream(path); 
           stream.write(array); 
       } catch (FileNotFoundException e1) 
       { 
          e1.printStackTrace(); 
       } 
    }