How to add files inside temporary directory in JUnit

Viewed 4339

I found two ways to create temporary directories in JUnit.

Way 1:

@Rule
public TemporaryFolder tempDirectory = new TemporaryFolder();

@Test
public void testTempDirectory() throws Exception {
    tempDirectory.newFile("test.txt");
    tempDirectory.newFolder("myDirectory");
    // how do I add files to myDirectory?
}

Way 2:

@Test
public void testTempDirectory() throws Exception {
    File myFile = File.createTempFile("abc", "txt");
    File myDirectory = Files.createTempDir();
    // how do I add files to myDirectory?
}

As the comment above mentions, I have a requirement where I want to add some temporary files in these temporary directories. Run my test against this structure and finally delete everything on exit.

How do I do that?

3 Answers

You can do it the same way you do it for real folders.

@Rule
public TemporaryFolder rootFolder = new TemporaryFolder();

@Test
public void shouldCreateChildFile() throws Exception {
    File myFolder = rootFolder.newFolder("my-folder");

    File myFile = new File(myFolder, "my-file.txt");
}

Using new File(subFolderOfTemporaryFolder, "fileName") did not work for me. Calling subFolder.list() returned an empty array. This is how I made it work:

@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

@Test
public void createFileInSubFolderOfTemporaryFolder() throws IOException {
    String subFolderName = "subFolder";
    File subFolder = temporaryFolder.newFolder(subFolderName);
    temporaryFolder.newFile(subFolderName + File.separator + "fileName1");

    String[] actual = subFolder.list();

    assertFalse(actual.length == 0);
}

There two ways to delete temp directory or temp file.Fist,delete the dirctory or file manually use file.delete() method,Second,delete the temp directory or file when program exis user file.deleteOnExist(). You can try this,I print the path to console,you can to check realy delte or not,I test on windows7 system.

File myDirectory = Files.createTempDir();
File tmpFile = new File(myDirectory.getAbsolutePath() + File.separator + "test.txt");
FileUtils.writeStringToFile(tmpFile, "HelloWorld", "UTF-8");
System.out.println(myDirectory.getAbsolutePath());
// clean
tmpFile.delete();
myDirectory.deleteOnExit();
Related