Monday, October 25, 2010

Java - Conversion Tips

Covert Long to String with Format


format : Returns a formatted string using the specified format string and arguments.


Long customerId = new Long(12);
System.out.println("Output..." + String.format("%04d", customerId));

Convert Double to String

Double doubleValue = new Double(40.5508995056152);
        double doubleVal = doubleValue;
        System.out.println("Double value.." + Double.toString(doubleVal));



String destinationDataType = destinationClass.toString();
String sourceValue = sourceFieldValue.toString();

SimplePropertyValueTO destinationFieldProperty = new SimplePropertyValueTO();
destinationFieldProperty.setPropertyName(param);
destinationFieldProperty.setPropertyType(destinationDataType);

if (destinationDataType.equalsIgnoreCase("string")) {
destinationFieldProperty.setPropertyStringValue(sourceValue);
} else if (destinationDataType.equalsIgnoreCase("short") || destinationDataType.equalsIgnoreCase("int")
|| destinationDataType.equalsIgnoreCase("long")) {

Long longDestinationValue = null;
longDestinationValue = longDestinationValue.parseLong(sourceValue);
destinationFieldProperty.setPropertyLongValue(longDestinationValue);
} else if (destinationDataType.equalsIgnoreCase("double")) {
Double doubleDestinationValue = null;
doubleDestinationValue = doubleDestinationValue.parseDouble(sourceValue);
} else if (destinationDataType.equalsIgnoreCase("boolean")) {
Boolean booleanDestinationValue = false;
booleanDestinationValue = booleanDestinationValue.parseBoolean(sourceValue);
} else if (destinationDataType.equalsIgnoreCase("Timestamp")) {
Timestamp timestampDestinationValue = null;
timestampDestinationValue = Timestamp.valueOf(sourceValue);
destinationFieldProperty.setPropertyDateValue(timestampDestinationValue);
}

Convert longblob data into Object
request = (Request) ByteConverter.getObject(requestMessage.getRequest());

public static byte[] getBytes(Object obj) throws java.io.IOException {
if (obj == null) {
return null;
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] data = bos.toByteArray();
return data;
}
public static Object getObject(byte[] objectData) throws IOException, ClassNotFoundException {
Object object = null;

if (objectData != null) {
ObjectInputStream in = null;
ByteArrayInputStream bin = new ByteArrayInputStream(objectData);
BufferedInputStream bufin = new BufferedInputStream(bin);

in = new ObjectInputStream(bufin);
object = in.readObject();
if (in != null) {
in.close();
}
}
return object;
}

No comments :

// Below script tag for SyntaxHighLighter