This Java Program will allow us to do RMS operations in File. In J2ME there is a package called javax.microedition.rms. This package is related to database operations in J2ME supported mobiles.The same is replicated using the file as Database.We can add new records,modify the existing records,delete the existing record in the file.
Main class:contains the necessary functions
Global:
package myPack; /* * *This midlet is will allow to modify the record data,Add new record * or delete the existing record */ import javax.microedition.lcdui.*; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class TestMidlet extends MIDlet implements CommandListener { Main m; private Command exit, start; private Display display; private Form form; public TestMidlet() { display = Display.getDisplay(this); exit = new Command("Exit", Command.EXIT, 1); start = new Command("Start", Command.EXIT, 1); form = new Form("Write To File"); form.addCommand(exit); form.addCommand(start); form.setCommandListener(this); } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { display.setCurrent(form); } public void commandAction(Command command, Displayable displayable) { if (command == exit) { try { destroyApp(false); } catch (MIDletStateChangeException e) { e.printStackTrace(); } notifyDestroyed(); } else if (command == start) { try { Main m = new Main(); Thread th = new Thread(m); th.start(); Alert alert = new Alert("Completed", "Data Written", null, null); alert.setTimeout(Alert.FOREVER); alert.setType(AlertType.ERROR); display.setCurrent(alert); } catch (Exception e) { e.printStackTrace(); Alert alert = new Alert("Error", "Cannot access file.", null, null); alert.setTimeout(Alert.FOREVER); alert.setType(AlertType.ERROR); display.setCurrent(alert); } } } }
Main class:contains the necessary functions
package myPack; /* * This class contains the functions to to modify the record data,Add new record * or delete the existing record */ import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; //import Screen.CommonFunctions; public class Main implements Runnable { byte[] byteStr; byte[] byteStr1; String result; String result1; String[] strArr = new String[100]; String[] strArr_1 = new String[100]; String[] strArr_2 = new String[100]; static int rows = 0; static int columns = 0; Main() { String str = "1|385632|Vijay2|ASE-Trainee2|"; byteStr = str.getBytes(); String str1 = "57|38565356|Vijay2|ASE-Trainee2|"; byteStr1 = str1.getBytes(); } public void run() { try { /* * Remove the comment lines for which the necessary function neds to be executed * Here addRecord is not commented. So when the midlet runs and executed addRecord will be called */ addRecord(byteStr, 0, byteStr.length);//parameter byteStr contains the data to be added // deleteRecord(5);//parameter 78 the Rec ID to be deleted // setRecord(6, byteStr1, 0, byteStr1.length); // parameter- 8 Rec ID to be replaced.parameter- byteStr1 is byte[] to be replaced } catch (IOException e) { e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } } /* * To add new record */ public void addRecord(byte[] data, int offset, int numBytes) throws IOException { OutputStream out = null; DataOutputStream dos = null; /* * To create new File */ FileConnection connection = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); if (connection.exists()) { /* * creating DataOutputStream to write the data */ out = connection.openOutputStream(connection.fileSize()); dos = new DataOutputStream(out); dos.write(data, offset, numBytes); dos.write("n".getBytes()); dos.flush(); dos.close(); connection.close(); } else { connection.create(); out = connection.openOutputStream(connection.fileSize()); dos = new DataOutputStream(out); dos.write(data, offset, numBytes); dos.write("n".getBytes()); dos.write(data, offset, numBytes); dos.write("n".getBytes()); dos.flush(); dos.close(); connection.close(); } } public String getDataFromFile() throws IOException { int chr; StringBuffer sb = new StringBuffer(); InputStream in = null; DataInputStream dis = null; FileConnection connection = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); if (connection.exists()) { in = connection.openInputStream(); while ((chr = in.read()) != -1) { sb.append((char) chr); } in.close(); connection.close(); return sb.toString(); } else { return "NO SUCH FILE"; } } /* * To delete a record */ public void deleteRecord(int recID) throws Throwable { OutputStream out = null; DataOutputStream dos = null; String[] strArrDel; int count = 0; ; try { result = getDataFromFile(); strArr = Global.parseStringArray(result, 'n'); for (int i = 0; i < strArr.length; i++) { System.out.println("SACHIN" + strArr[i]); } strArrDel = findPositionAndDelete(strArr, recID); String s = ""; for (int i = 0; i < strArrDel.length; i++) { s = s + strArrDel[i] + "n"; } byte[] afterDeletion = new byte[s.getBytes().length]; afterDeletion = s.getBytes(); FileConnection connection1 = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); if (connection1.exists()) { connection1.truncate(0); out = connection1.openOutputStream(); dos = new DataOutputStream(out); dos.write(afterDeletion, 0, afterDeletion.length); dos.flush(); dos.close(); connection1.close(); } else { connection1.create(); } } catch (IOException e) { e.printStackTrace(); } } public String[] findPositionAndDelete(String[] strArr1, int recID) throws Throwable { int i = 1, j = 1; boolean blFound=false; String[] strArrNew = new String[strArr1.length - 1]; strArrNew[0] = strArr1[0]; for(int k=0;k<strArr1.length;k++){ if(recID==Integer.parseInt(strArr1[k].substring(0, strArr1[k].indexOf('|')))){ blFound=true; } } if(blFound){ while (i < strArr1.length && j <strArr1.length - 1) { if (recID == Integer.parseInt(strArr1[i].substring(0, strArr1[i] .indexOf('|')))) { i++; continue; } else { strArrNew[j] = strArr1[i]; i++; j++; continue; } } return strArrNew; }else{ throw new Throwable("YOU HAVE ENTERED INVALID RECORD ID"); } } /* * To modify the existing record */ public void setRecord(int recID, byte[] newData, int offset, int numBytes) throws Throwable { OutputStream out = null; DataOutputStream dos = null; result1 = getDataFromFile1(); strArr_2 = Global.parseStringArray(result1.trim(), 'n'); for (int j = 0; j < strArr_2.length; j++) { } strArr_1 = Global.parseStringArray(result1, 'n'); // for (int j = 0; j < strArr123.length; j++) { // System.out.println(" strArr123[" + j + "]" + strArr123[j]); // } String[] strArrUpdate = findPositionAndUpdate(strArr_1, recID, newData, offset, numBytes); // for (int i = 0; i < strArrUpdate.length; i++) { // System.out.println("CHEERS" + strArrUpdate[i]); // } String s1 = ""; for (int i = 0; i < strArrUpdate.length; i++) { s1 = s1 + strArrUpdate[i] + "n"; } s1 = s1.trim(); byte[] afterUpdtation = new byte[s1.getBytes().length]; afterUpdtation = s1.getBytes(); FileConnection connection2 = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); if (connection2.exists()) { connection2.truncate(0); out = connection2.openOutputStream(); dos = new DataOutputStream(out); dos.write(afterUpdtation, 0, afterUpdtation.length); dos.flush(); dos.close(); connection2.close(); } else { connection2.create(); } } public String[] findPositionAndUpdate(String[] strArr1, int recID, byte[] newData, int offset, int numBytes) { int i = 1, j = 1; String[] strArrNew = new String[strArr1.length]; StringBuffer sbNew = new StringBuffer(); while (i <= strArr1.length) { if (recID == Integer.parseInt(strArr1[i - 1].substring(0, strArr1[i - 1].indexOf('|')))) { String str = strArr1[i - 1].substring(strArr1[i - 1] .indexOf('|'), strArr1[i - 1].length()); for (int k = offset; k < numBytes; k++) { sbNew.append((char) (newData[k])); } String strNew = sbNew.toString(); strArrNew[i - 1] = strNew; i++; continue; } else { strArrNew[i - 1] = strArr1[i - 1]; i++; } } return strArrNew; } public String getDataFromFile1() throws IOException { System.out.println("STARTED"); int chr; StringBuffer sb = new StringBuffer(); InputStream in = null; DataInputStream dis = null; System.out.println("FILE CONNECTED"); FileConnection connection5 = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); if (connection5.exists()) { in = connection5.openInputStream(); in.mark(0); in.reset(); System.out.println("MARK HAS BEEN SET"); while ((chr = in.read()) != -1) { sb.append((char) chr); } in.close(); connection5.close(); return sb.toString(); } else { return "NO SUCH FILE"; } } public void obtainInfo() throws Throwable { result = getDataFromFile2(); strArr = Global.parseStringArray1(result, '|'); String[] strConverted = new String[strArr.length - 1]; for (int i = 0; i < strArr.length; i++) { System.out.println("strArr[" + i + "]" + strArr[i]); } for (int i = 0; i < strArr.length - 1; i++) { strConverted[i] = strArr[i]; } // for (int i = 0; i < strConverted.length; i++) { // System.out.println("strConverted[" + i + "]" + strConverted[i]); // } } public String getDataFromFile2() throws IOException { String[] strArr = new String[200]; System.out.println("STARTED"); int chr; StringBuffer sb = new StringBuffer(); InputStream in = null; DataInputStream dis = null; FileConnection connection = (FileConnection) Connector.open( "file:///root1/TCSFI/Data/" + "mynewfile.txt;append=true", Connector.READ_WRITE); System.out.println("CONNECTION OPEN"); if (connection.exists()) { in = connection.openInputStream(); while ((chr = in.read()) != -1) { sb.append((char) chr); } in.close(); connection.close(); return sb.toString(); } else { System.out.println("NO SUCH FILE"); return "NO SUCH FILE"; } } public int returnColumns() { return columns; } }
Global:
package myPack; import java.util.Date; import java.util.Random; import java.util.TimeZone; public class Global { final public static String[] parseStringArray( final String argStrToBeParsed, final char argChDelim) throws Throwable { String[] strArr = null; String strToBeParsed = argStrToBeParsed; String strTemp = ""; int inIndex = 0; int lnlen = 0, intemp = -1; try { if (strToBeParsed.endsWith("" + argChDelim)) { strToBeParsed = strToBeParsed.substring(0, strToBeParsed .length() - 1); } while (strToBeParsed.indexOf(argChDelim) != -1) { strTemp = ""; inIndex = strToBeParsed.indexOf(argChDelim); strTemp = strToBeParsed.substring(0, inIndex); strArr = addStringElementToArray(strArr, lnlen, strTemp); lnlen++; strToBeParsed = strToBeParsed.substring(inIndex + 1); } if (strToBeParsed.indexOf(argChDelim) == -1) { strArr = addStringElementToArray(strArr, lnlen, strToBeParsed); lnlen++; } } catch (Exception e) { } return strArr; } final public static String[] addStringElementToArray(String[] sArrayOld, final int iPos, final String sEl) throws Throwable { try { if (iPos >= 0) { if (sArrayOld == null || iPos >= sArrayOld.length) { String sArrayNew[] = new String[iPos + 1];// +1 only is if (sArrayOld != null) { System.arraycopy(sArrayOld, 0, sArrayNew, 0, sArrayOld.length); } sArrayOld = null; sArrayOld = sArrayNew; } sArrayOld[iPos] = sEl; } } catch (Exception e) { e.printStackTrace(); } return sArrayOld; } final public static String[] parseStringArray1( final String argStrToBeParsed, final char argChDelim) throws Throwable { String[] strArr = null; String strToBeParsed = argStrToBeParsed; String strTemp = ""; int inIndex = 0; int lnlen = 0, intemp = -1; try { if (strToBeParsed.endsWith("" + argChDelim)) { strToBeParsed = strToBeParsed.substring(0, strToBeParsed .length() - 1); } while (strToBeParsed.indexOf(argChDelim) != -1) { strTemp = ""; inIndex = strToBeParsed.indexOf(argChDelim); strTemp = strToBeParsed.substring(0, inIndex); System.out.println("length : " + strTemp.length()); if (strTemp != null) { for (int i = 0; i < strTemp.length(); i++) { intemp = strTemp.charAt(i); System.out.println("char at value... " + intemp); if (intemp == 13) { strTemp = strTemp.substring(2); System.out.println("substring ... " + strTemp + " whose length is :" + strTemp.length()); } } } System.out.println("after length : " + strTemp.length()); strArr = addStringElementToArray(strArr, lnlen, strTemp); lnlen++; strToBeParsed = strToBeParsed.substring(inIndex + 1); } if (strToBeParsed.indexOf(argChDelim) == -1) { strArr = addStringElementToArray(strArr, lnlen, strToBeParsed); lnlen++; } } catch (Exception e) { } return strArr; } public static String[] removeNullValues( String[] strArrOld) { String[] strArrNew = null; int inLen = 0, k = 0; try { if (strArrOld != null && strArrOld.length > 0) { for (int i = 0; i < strArrOld.length; i++) { if (strArrOld[i] != null) { inLen++; } } strArrNew = new String[inLen]; for (int j = 0; j < strArrOld.length; j++) { if (strArrOld[j] != null) { strArrNew[k] = strArrOld[j]; k++; } } } } catch (Throwable t) { t.printStackTrace(); return null; } return strArrNew; } }