There is a code:

FILENAME= "file"; url = new URL("1231"); new ParseTask(url,FILENAME).execute(); url = new URL("1231"); FILENAME="file1"; new ParseTask(url,FILENAME).execute(); } catch (IOException e) { e.printStackTrace(); } } public class ParseTask extends AsyncTask<Void, Void, String> { HttpURLConnection urlConnection = null; BufferedReader reader = null; String resultJson = ""; private URL url; public String file; public ParseTask(URL url, String file) { this.url = url; this.file=file; } @Override protected String doInBackground(Void... params) { // получаем данные с внешнего ресурса try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return resultJson; } @Override protected void onPostExecute(String strJson) { try { // отрываем поток для записи BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( openFileOutput(FILENAME, MODE_PRIVATE))); // пишем данные bw.write(strJson); // закрываем поток bw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 

For some reason, it only works with the latest file, how to make it work with both files?

    1 answer 1

    The whole problem is that you use the value of the global variable FILENAME in the onPostExecute method.
    Accordingly, in the asynchronous world, the call of this method does not occur instantly (asynchronously), and the global variable at the time of the method call contains the value file1 .

    You also have a class field with the name of the file, so you should use it:

     // отрываем поток для записи BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( openFileOutput(this.file, MODE_PRIVATE)));