Sunday, May 1, 2011

File Connection Read Write

private synchronized String readDataFromFile(String path) {
        String fileData = null;
      try {
         FileConnection fc = (FileConnection) Connector.open(path);
         if(!fc.exists()){
             fc.mkdir();
         }
         InputStream is = fc.openInputStream();
         byte b[] = new byte[1024];
         int length = is.read(b, 0, 1024);
         fileData = new String(b, 0, length);
         System.out.println("Content in File : "+ new String(b, 0, length));
         is.close();
         fc.close();

         }
      catch(Exception e){
         e.printStackTrace();
         }
      return fileData;
    }





public void WriteFile(String data){
       

                try {                   
                    FileConnection fconn = (FileConnection)Connector.open("file:///e:/Data.txt", Connector.READ_WRITE);                   

                    if(!fconn.exists())
                        fconn.create();

                    OutputStream os = fconn.openOutputStream(fconn.fileSize());
                    DataOutputStream dos = new DataOutputStream(os);
                    dos.write(data.getBytes("UTF8"));
                    dos.write("\n".getBytes("UTF8"));
                    //dos.writeUTF(meterReading);
                    dos.close();
                    os.close();
                    fconn.close();
                }
                catch (IOException ex) {
                        ex.printStackTrace();
               }
          
      }

No comments:

Post a Comment