How to add files inside temporary directory in JUnit

Vicky :

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?

Sasha Shpota :

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");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130032&siteId=1