Feb 4, 2009

Copy file pada j2me

2 hari yang lalu saya benar-benar dibuat pusing dengan algoritma copy data pada J2ME. Sebenarnya copy data akan sangat mudah dilakukan dengan class File, tetapi karena saya ingin menerapkan konsep Java Persistence untuk beberapa alasan saya putuskan untuk ngotot menggunakan class FileConnection. Dan akhirnya dengan ridho dan rahmat Alloh saya temukan algoritma berikut untuk meng-copy file dengan J2ME

public boolean AddImage(String aImageSourcePath) {
FileConnection SourceConnection = null;
FileConnection DestinationConnection = null;
InputStream SourceInputStream = null;
OutputStream DestinationOutputStream = null;
long LengthNotWriteDataYet = 0;
long SourceFileSize = 0;
long CopyDataCounter = 0;

try {
SourceConnection = (FileConnection) Connector.open(aImageSourcePath, Connector.READ);
DestinationConnection = (FileConnection) Connector.open(AppDefaultData.getAppGaleryImage() + SourceConnection.getName(), Connector.READ_WRITE);

// create file
if (! DestinationConnection.exists()) {
DestinationConnection.create();
} else {
DestinationConnection.delete();
DestinationConnection.create();
}

byte[] TempWriteData = new byte[1024];
SourceFileSize = SourceConnection.fileSize();
// in first length of LengthNotWriteDataYet same with length of Source File, because no other data have been write
LengthNotWriteDataYet = SourceFileSize;

SourceInputStream = SourceConnection.openInputStream();
DestinationOutputStream = DestinationConnection.openOutputStream();
// copy Source File
int copyFlag;
while (LengthNotWriteDataYet > 1024) {
copyFlag = SourceInputStream.read(TempWriteData, 0, 1024); // salah nang bagian 0
if (copyFlag != -1) {
DestinationOutputStream.write(TempWriteData, 0, copyFlag);
}

CopyDataCounter++;
LengthNotWriteDataYet = LengthNotWriteDataYet - 1024;
}

// copy more data
int NotBeenWriteDataLength = Integer.parseInt(Long.toString(LengthNotWriteDataYet)); // convert from long to integer.
byte[] NotBeenWriteData = new byte[NotBeenWriteDataLength];
copyFlag = SourceInputStream.read(NotBeenWriteData, 0, NotBeenWriteDataLength);
DestinationOutputStream.write(NotBeenWriteData, 0, copyFlag);

} catch (Exception ex) {
except = ex;
return false;
} finally {
try {
SourceInputStream.close();
} catch (IOException ex) {
except = ex;
return false;
}
try {
DestinationOutputStream.close();
} catch (IOException ex) {
except = ex;
return false;
}
try {
SourceConnection.close();
} catch (IOException ex) {
except = ex;
return false;
}
try {
DestinationConnection.close();
} catch (IOException ex) {
except = ex;
return false;
}
}

return true;
}


Semoga bermanfaat.
dhimas_oke said...

artikel yg sangat bermanfaatr.
mas,ada source code yg lengkap g mas..hehe
makasih.

dhimas_oke said...

info yg sangat berguna.hehe
mas,ada source lengkapnya ga??bagi dong.makasih..

Unknown said...

Thanks infonya gan

Powered by Blogger.

Whatsapp Button works on Mobile Device only

Start typing and press Enter to search