JUnit – Create Temporary File/Folder using TemporaryFolder @Rule

Many times we need to create junit unit tests where we need to create temporary folders or temporary files for executing the testcase. Many times we rely on having a temp folder at particular location and generate all temp files there. Well, it has it’s own disadvantages. Major disadvantage is that you need to cleanup these files manually.

Junit comes with TemporaryFolder class which you can use for generating temp folders.

The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). Whether the deletion is successful or not is not checked by this rule. No exception will be thrown in case the deletion fails.

Sample usage of TemporaryFolder Rule is :

public static class HasTempFolder {
        @Rule
        public TemporaryFolder folder= new TemporaryFolder();
 
        @Test
        public void testUsingTempFolder() throws IOException {
                File createdFile= folder.newFile("myfile.txt");
                File createdFolder= folder.newFolder("subfolder");
                // ...
        }
 }

Let’s make a quick testcase and see how it works.

import java.io.File;
import java.io.IOException;

import junit.framework.Assert;

import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class TemporaryFolderTest {
   
   @Rule
   public TemporaryFolder tempFolder = new TemporaryFolder();
  
   @Test
   public void testWrite() throws IOException {
     // Create a temporary file.
     final File tempFile = tempFolder.newFile("tempFile.txt");
  
     // Write something to it.
     FileUtils.writeStringToFile(tempFile, "hello world");
  
     // Read it from temp file
     final String s = FileUtils.readFileToString(tempFile);
  
     // Verify the content
     Assert.assertEquals("hello world", s);
     
     //Note: File is guaranteed to be deleted after the test finishes.
   }
 }

It’s really easy and useful feature of Junit. Use it next time and you will find it a great help.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

10 thoughts on “JUnit – Create Temporary File/Folder using TemporaryFolder @Rule”

  1. Hi Lokesh,

    Thanks for sharing. It’s helpful.
    But I see some temp files getting created and still remain in temp location after running junit code. Can you please let me know is there anyway to avoid this.

    Thanks,
    Sri

    Reply
      • I’m afraid that the claim “File is guaranteed to be deleted after the test finishes” is not correct. From the Javadoc, “The TemporaryFolder Rule allows creation of files and folders that should be deleted when the test method finishes (whether it passes or fails). Whether the deletion is successful or not is not checked by this rule. No exception will be thrown in case the deletion fails.”

        Reply
  2. Hi…….Dear Lokesh,

    I m happy to say I m following you site since last year It really
    helpful and beneficial.

    1.Today I asked how many question you can create in java for a class.?
    2.How could you know that how many connections are opened in hibernate ?
    3.How can you find size of object in using java program?
    4.How could count the repeated word/letters in String/word w/o using collection?

    I really not able to find these question on net …..so please help here.

    Thanks
    Regards
    kaushal

    Reply
    • Hi Kaushal, You could not find the answers because they cannot be directly programmed using normal java programming. I tried to quick google search for your answers and below are answers which make sense to me.

      1) I really do not understand the question properly. Please elaborate.

      2) Hibernate does not manage connection pools and it ask the third party connection pool implementations for opening/closing a conneection; so you cannot ask this information from hibernate. One good way is to directly ask from connected database itself. e.g. for MySQL there is a command “show processlist”. It retuen the number of connections opened at any time + 1 (reserved for super user).

      https://dev.mysql.com/doc/refman/8.0/en/show-processlist.html

      3) This one is also tricky and there is no direct solution. Please go through information in given SO thread. Answer mentioning “java.lang.instrument.Instrumentation” makes more sense to me.

      https://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object

      4) This should not be too hard to solve. I wrote a quick example. Please modify as per your need.

      public class CountDuplicates
      {
         public static void main(String[] args)
         {
            String s = "ABC DEF ABC GEH IJL LMO ABCD";  
            System.out.println(count(s, 'A'));
         }
         
         public static int count(String word, Character ch)  
         {  
             int pos = word.indexOf(ch);  
             return pos == -1 ? 0 : 1 + count(word.substring(pos+1),ch);  
         } 
      }
      
      Output: 3
      

      I hope it helps.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.