Saturday, September 8, 2018

Finding the Size of Object By Converting to String

package com.nagaraju.simplejson;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;

public class ObjectSize {

public static void main(String[] args) {
checkStringSizeWithByteArrayOutputStream("Nagaraju");
checkStringSizeWith("Nagaraju");
}

public static void checkStringSizeWithByteArrayOutputStream(String list) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(baos);
objOut.writeObject(list);
Integer value = baos.toByteArray().length;
System.out.println("Given String::" + list + ":Size:" + value);
objOut.close();
} catch (IOException e) {
System.out.println("IOException Occured");
}
}

public static void checkStringSizeWith(String list) {
try {
int value = list.getBytes("UTF-8").length;
System.out.println("String Size By Providing Encoding::" + value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

Out Put:

Given String::Nagaraju:Size:15
String Size By Providing Encoding::8


No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...