2

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

ファイルは保存されています。ファイルを読み取ることもできますが、すべて問題ありませんが、この行を見てください

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

ファイルの保存時に保存される文字列の長さを計算しています。あるアクティビティでファイルを保存し、別のアクティビティから読み取っています。アプリケーションはファイルをローカルに一度保存するため、長さを取得できませんでした毎回文字列を返すので、動的にサイズを割り当てる方法はありますか?char[] inputBuffer

4

1 に答える 1

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を使用してください。

于 2013-02-04T05:44:01.190 に答える