Monday 17 March 2014

Tech Talk... Creating a temporary file using java

Template:

File tempFile = File.createTempFile(<temp-file-name>, <temp-file-extension>);

Using the above template would create a file with name <temp-file-name> and extension <temp-file-extension>.

Code sample:

File tempFile = File.createTempFile("mytempfile", ".txt");

Where such code gets useful:

Mostly, I find it very useful when writing unit test cases in java which require to test scenarios where a file creation is required, because, this way, I don't have have to worry about which OS I am on, what location should I choose to create a temporary file etc. In the setup method in my unit test, I can create the file and in the teardown method i can call delete() on this file to ensure that the file gets created before I run my testcase and gets deleted after the testcase is complete. 

No comments:

Post a Comment