0

Working on a InputStream which is constructed from String. Can someone help me with any predefined method to get the size of InputStream or String? I am using below method but its giving me fairly different size when I save my string into File. PS:- I need to perform a operation according to size before saving it to file. I need to process a fairly large data around 2GB in size.

  public static float getSizeInGB(String data) {
        float unit = 1024.0f;
        float dataBytes = data.getBytes(StandardCharsets.UTF_8).length * 2;
        if (data == null) {
            return 0;
        }
        return dataBytes/ (unit * unit * unit);
    }
Ayush Somani
  • 146
  • 11
  • 1
    If you want exact results, you should not use floating point values. Further, there’s no sense in performing a `null`-check on the input value *after* the operation that would fail with `null`. Further, the length of the byte array will only match the size of a written file (or input stream), if you use the same character encoding for both operations. In that case, they should match exactly, so why are you multiplying the number of bytes with two? And why don’t you use the byte array returned by `getBytes` right for your other operation? Using the same array precludes having different lengths. – Holger Jan 18 '21 at 13:50

1 Answers1

0

according to this post https://stackoverflow.com/questions/88838/how-to-convert-strings-to-and-from-utf8-byte-arrays-in-java/88863#88863

you can do it by :

byte[] b = data.getBytes("UTF-8");
System.out.println(b.length);