import java.io.InputStream; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; /**
* This class to read file from memory and create a file on phone memory
* @author Mohammad Abu Hmead
* 08.03.11
*/
public class CreateAndReadFileOnAndFromMemory {
public static final String FILE_LOCATIO_IN_PHOTOS=System.getProperty("fileconn.dir.photos");
public static final String FILE_LOCATIO_IN_VIDEOS=System.getProperty("fileconn.dir.videos");
public static final String FILE_LOCATIO_IN_TONES=System.getProperty("fileconn.dir.tones");
public static final String FILE_LOCATIO_ON_MEMORY_CARD=System.getProperty("fileconn.dir.memorycard");
private String fileLocationURL="Not specified yet";
public CreateAndReadFileOnAndFromMemory(String fileLocation,String fileNameWithItsExtension)
{
fileLocationURL=fileLocation+fileNameWithItsExtension;
}
public String getFileLocationURL(){
return fileLocationURL;
}
public void setFileLocationURL(String fileLocationURL) {
this.fileLocationURL = fileLocationURL;
}
public void writeIntoFile(String textToBeWritten) throws Exception
{
FileConnection fileConnection;
fileConnection = (FileConnection) Connector.open(fileLocationURL, Connector.READ_WRITE);
if(!fileConnection.exists())
fileConnection.create();
OutputStream outputStream=fileConnection.openOutputStream();
outputStream.write(textToBeWritten.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
fileConnection.close();
}
public boolean createFileOnMem(byte[] fileBs) throws Exception
{
boolean isCreated=false;
try {
FileConnection fileConnection;
fileConnection = (FileConnection) Connector.open(fileLocationURL, Connector.READ_WRITE);
if(!fileConnection.exists())
fileConnection.create();
OutputStream outputStream=fileConnection.openOutputStream();
outputStream.write(fileBs);
outputStream.flush();
outputStream.close();
fileConnection.close();
isCreated=true;
} catch (Exception e) {
}
return isCreated;
}
public byte[] readFileByts() throws Exception
{
byte[] filebBs=null;
FileConnection fileConnection = (FileConnection)
Connector.open(fileLocationURL, Connector.READ_WRITE);
if(fileConnection.exists())
{
filebBs=new byte[(int)fileConnection.fileSize()];
InputStream is=fileConnection.openInputStream();
is.read(filebBs, 0, filebBs.length);
is.close();
is=null;
fileConnection.close();
}
return filebBs;
}
public boolean deleteTheFile()
{
boolean isDeleted=false;
FileConnection fileConnection;
try {
fileConnection = (FileConnection) Connector.open(fileLocationURL, Connector.READ_WRITE);
if(fileConnection.exists())
{
fileConnection.delete();
isDeleted=true;
}
} catch (Exception ex) {
}
return isDeleted;
}
}