14

please give me a sample code for read/write text file in blackberry application.

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114

2 Answers2

29

My code snippet for string read/write files:

private String readTextFile(String fName) {
  String result = null;
  FileConnection fconn = null;
  DataInputStream is = null;
  try {
   fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
   is = fconn.openDataInputStream();
   byte[] data = IOUtilities.streamToBytes(is);
   result = new String(data);
  } catch (IOException e) {
   System.out.println(e.getMessage());
  } finally {
   try {
    if (null != is)

     is.close();
    if (null != fconn)
     fconn.close();
   } catch (IOException e) {
    System.out.println(e.getMessage());
   }
  }
  return result;
 }

private void writeTextFile(String fName, String text) {
  DataOutputStream os = null;
  FileConnection fconn = null;
  try {
   fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
   if (!fconn.exists())
    fconn.create();

   os = fconn.openDataOutputStream();
   os.write(text.getBytes());
  } catch (IOException e) {
   System.out.println(e.getMessage());
  } finally {
   try {
    if (null != os)
     os.close();
    if (null != fconn)
     fconn.close();
   } catch (IOException e) {
    System.out.println(e.getMessage());
   }
  }
 }
Dhruv
  • 1,129
  • 2
  • 13
  • 32
Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114
  • 2
    It's better to use Connector.READ_WRITE instead of Connector.WRITE (in my case the second does not work). – Anthony Oct 15 '10 at 11:05
4

Using

FileConnection Interface

rahul
  • 184,426
  • 49
  • 232
  • 263