2013-02-04 64 views
2

我想提出一個XML文件,並保存在我的設備代碼如下文件保存在Android

HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost("http://xx:xx:xx:xx:yy/LoginAndroid.asmx/login"); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     String responseBody = EntityUtils.toString(response.getEntity()); 
     //Toast.makeText(getApplicationContext(),"responseBody: "+responseBody,Toast.LENGTH_SHORT).show(); 

     //saving the file as a xml 
     FileOutputStream fOut = openFileOutput("loginData.xml",MODE_WORLD_READABLE); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut); 
     osw.write(responseBody); 
     osw.flush(); 
     osw.close(); 

     //reading the file as xml 
     FileInputStream fIn = openFileInput("loginData.xml"); 
     InputStreamReader isr = new InputStreamReader(fIn); 
     char[] inputBuffer = new char[responseBody.length()]; 
     isr.read(inputBuffer); 
     String readString = new String(inputBuffer); 

文件是保存我還可以讀取該文件的每一件事情是確定的,但看這條線

char[] inputBuffer = new char[responseBody.length()];

它計算可被保存在保存的file.I現在的儲蓄在一個Acivity的文件,並從另一個活動閱讀它和我的應用程序將文件保存到本地,一旦時間字符串的長度,所以我可以不能夠以獲得該返回的長度每次有n個字符串那麼有什麼辦法動態地分配char[] inputBuffer的大小?

回答

0

您可以在另一個活動中使用下面的代碼來讀取文件。看看BufferedReader課。

InputStream instream = new FileInputStream("loginData.xml"); 

// if file the available for reading 
if (instream != null) { 
    // prepare the file for reading 

    InputStreamReader inputreader = new InputStreamReader(instream); 
    BufferedReader buffreader = new BufferedReader(inputreader); 

    String line; 

    // read every line of the file into the line-variable, on line at the time 
    while (buffreader.hasNext()) { 
    line = buffreader.readLine(); 
    // do something with the line 

    } 

} 

編輯

上面的代碼是爲讀文件工作正常,但如果你只是想分配char[] inputBuffer dynamicall的大小,那麼你可以使用下面的代碼。

InputStream is = mContext.openFileInput("loginData.xml"); 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
byte[] b = new byte[1024]; 
while ((int bytesRead = is.read(b)) != -1) { 
    bos.write(b, 0, bytesRead); 
} 
byte[] inputBuffer = bos.toByteArray(); 

現在,根據需要使用inputBuffer。

+0

我需要知道有多少字符不行然後 **它給我錯誤'方法hasNext()是未定義的類型BufferedReader' ** – Anirban

+0

答案更新,請看看。希望這是你所問的。 –

+0

againg錯誤''不能對類型上下文''的非靜態方法openFileInput(String)進行靜態引用''InputStream is = Context.openFileInput(「loginData.xml」);' – Anirban