在android上保存文件

时间:2013-02-04 02:36:09

标签: android xml android-file input-buffer

我正在创建一个xml文件并将其保存在我的设备代码中

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);

FIle正在保存我也可以读取文件,但是看看这一行

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

它正在计算保存文件时保存的字符串长度。我将文件保存在一个Acivity中并从另一个活动中读取它,我的应用程序将在本地保存文件一次因此我无法获得每次返回字符串的长度那么有没有办法动态分配char[] inputBuffer的大小?

1 个答案:

答案 0 :(得分: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。