Home > Mobile >  Need to wait for file to be available
Need to wait for file to be available

Time:12-21

Below is my code where I need to convert my JSON file to an Excel file. Loading the JSON from another method will take some time, so I need to wait till the file is present.

public class converter2_ES {

    @Test
    public void main() throws Exception { 
        LocalDateTime date = LocalDateTime.now();
        DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH-mm-ss");
        String formatedate =date.format(dateformat);
        Workbook workbook = new Workbook(".//json_files//elastic_search.json");      
        //workbook.save(".//output-" formatedate ".xlsx");  
        workbook.save(".//Excel_files//es_files//ES-" formatedate ".xlsx");

        System.out.println("Elastic_searchjson file converted successfully");
    }
}

CodePudding user response:

Question

In my test, the file .//json_files//elastic_search.json is actually written by another test. How can I make sure that this test is run after the test that writes the file to disk?

This question had to be extracted from the comments.

Answer

The answer is, it depends...

Generally speaking, tests should not have temporal coupling with one another. Meaning that test2() should not rely on the outcome or behavior of test1().

There are many ways of fixing this problem, it could be fixed by having your tests in two different classes each having their own particular setup() methods with an @BeforeEach annotation.

Another solution is to make sure that the tests run in the correct order. There are ways of adding order via the @Test annotation depending on which testing framework you're using.

CodePudding user response:

You should make a async implementation that is, you should wait until previous task has been completed to proceed with next task, you can refer to this simple tutorial ANDROID - HTTP REQUEST USING ASYNCTASK TUTORIAL IN JAVA

Below is the code sample you can refer to:

public class MainActivity extends AppCompatActivity {
    private Button btn;
    private EditText time;
    private TextView res;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        time = findViewById(R.id.in_time);
        btn = findViewById(R.id.btn_start);
        finalRes = findViewById(R.id.res);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();
                runner.execute(sleepTime);
            }
        });
    }

    private class AsyncTaskRunner extends AsyncTask<String, String, 
    String> {

        private String resp;
        ProgressDialog progressDialog;

        
        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this,
                    "PleaseWait",
                    "Loading" time.getText().toString()  "secs");
        }

        @Override
        protected String doInBackground(String... params) {
            publishProgress("TimeSpent...");
            try {
                int time = Integer.parseInt(params[0])*1000;

                Thread.sleep(time);
                resp = "Time Spent"   params[0]   "secs";
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            return resp;
        }


        @Override
        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation
            progressDialog.dismiss();
            finalRes.setText(result);
        }

    }
}

CodePudding user response:

If you want to wait for a file to be created by another program:

  • How to wait on file creation - which has examples on how to use the WatchService. However, note that you get an event to indicate that a file has been created, but you don't get one to say that file creation (i.e. writing) has completed. So, depending on how the save() method works, you will probably need to check the file size of modification timestamp to see when they stop changing.

From my reading of the javadocs, the WatchService should report file events for files created by the current program as well, but there may be better ways. For example, if you want to wait for a file to be created by another thread:

  • If you are using naked threads or thread subclasses, use Thread.join() to wait for the thread doing the creation to finish.
  • If you are using an ExecutorService rather than naked threads, keep the Future object returned when you submit a task and use it to detect when the task has completed.

If you are doing this in some test code, the WatchService may be overkill. A simple polling loop (with a sleep) that tests to see that the target file has been created may be sufficient.


These won't be appropriate if you code is part of (say) a Swing or JavaFX app. These have their own ways to perform a long running task and act on its completion. (If you simply wait for the task in in the UI event loop, you will block the event loop.

Android will be different again ...

  •  Tags:  
  • java
  • Related