2013-02-04 45 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