Search code examples
androidxmlandroid-fileinput-buffer

file saving on android


I am making a xml file and saving it on my device code follows

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 is saving I can also read the file every thing is ok but look at this line

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

it is calculating string length which is saved at the time of Saving the file.I am saving the file in one Acivity and reading it from another activity and my application will save the file locally once so I could not be able to get the length of that return string every time So is there any way to allocate the size of char[] inputBuffer dynamically?


Solution

  • you can use the below code in your another activity to read the file. Have a look at BufferedReader class.

    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 
    
      }
    
    }
    

    Edit:

    The above code is working fine for reading a file, but if you just want to allocate the size of char[] inputBuffer dynamicall then you can use the below code.

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

    Now , make use inputBuffer as you want.