2011-05-31 38 views
0

我想從互聯網上取得XML,但每次從網絡取得XML都會讓我的應用程序變慢,所以我想拿取並保存在本地目錄中,下次我打開應用程序,然後在後端將xml再次從互聯網複製到我的xml如何在黑莓本地保存xml文件?

如何做到這一點,是否還有其他解決此問題的好方法?

+0

是不是有一個應用程序文件夾?是強制使用xml嗎? – Aravind 2011-05-31 05:51:36

回答

1

請使用以下功能將文件寫入SD卡。

private static String APP_DOC_DIR = "file:///SDCard/BlackBerry/documents/MyAPP/"; 

public static void writeToSD(String fileName, String fileContent){ 
    FileConnection fconn = null; 
     // APP_DOC_DIR is the directory name constant. 
    try { 
     FileConnection fc = (FileConnection)Connector.open(APP_DOC_DIR); 
    // If no exception is thrown, the URI is valid but the folder may not exist. 
    if (!fc.exists()) 
    { 
     fc.mkdir(); // create the folder if it doesn't exist 
    } 
    fc.close(); 


     fconn = (FileConnection) Connector.open(APP_DOC_DIR + fileName ,Connector.READ_WRITE);   
     if (!fconn.exists()) { 
      fconn.create(); 
     } 
     fconn.setReadable(true); 
     fconn.setWritable(true); 
     OutputStream os = fconn.openOutputStream(); 
     os.write(fileContent.getBytes("UTF8")); 
     os.flush(); 
     os.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (fconn!=null) { 
      try { 
       fconn.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

從SD卡讀取文件如下。

public static String readFromSD(String fileName) 
    { 
     String resultString = ""; 
     int BUFFER_SIZE = 10000; 
     InputStream inputStream = null; 
     FileConnection fconn; 
     try { 
      fconn = (FileConnection) Connector.open(APP_DOC_DIR + fileName, Connector.READ); 
      if (fconn.exists()) 
      { 
       inputStream = fconn.openInputStream(); 
      } 
      else 
      { 
       return ""; 
      } 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      byte[] buffer = new byte[BUFFER_SIZE]; 
      while (true) { 
       int bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE); 
       if (bytesRead == -1) 
         break; 
       byteArrayOutputStream.write(buffer, 0, bytesRead); 
      } 
      byteArrayOutputStream.flush(); 
      byte[] result = byteArrayOutputStream.toByteArray(); 
      byteArrayOutputStream.close(); 
      //resultString = new String(result,"UTF8"); 
      resultString = new String(result); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return resultString; 
    } 
+0

然而我沒有測試它,但至少肯定有人敢於思考和回答,謝謝先生...... – 2011-05-31 09:10:18