Created
February 13, 2012 12:36
-
-
Save tblachowicz/1816555 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.IOException; | |
public class TemporaryDirectory { | |
private File temporaryDirectory; | |
public boolean create(String prefix) throws IOException { | |
File temporaryFile = File.createTempFile(prefix, ".tmp"); | |
try { | |
temporaryDirectory = new File(temporaryFile.getParentFile(), | |
String.format("%s%d", prefix, System.currentTimeMillis())); | |
return temporaryDirectory.mkdir(); | |
} finally { | |
temporaryFile.delete(); | |
} | |
} | |
public boolean remove() { | |
return temporaryDirectory.delete(); | |
} | |
public File newFile(String name) throws IOException { | |
File newFile = new File(temporaryDirectory, name); | |
if(!newFile.createNewFile()) { | |
throw new IOException(String.format( | |
"Couldn't create new file '%s' in directory'%'", | |
name, temporaryDirectory)); | |
} | |
return newFile; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static org.junit.Assert.*; | |
import static org.hamcrest.CoreMatchers.*; | |
import java.io.File; | |
import java.io.IOException; | |
import org.junit.After; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class TemporaryDirectoryTest { | |
TemporaryDirectory tempDir = new TemporaryDirectory(); | |
@Before | |
public void setUp() throws IOException { | |
tempDir.create("TemporaryDirectoryTest"); | |
} | |
@After | |
public void tearDown() { | |
tempDir.remove(); | |
} | |
@Test | |
public void test() throws IOException { | |
File myFile = tempDir.newFile("myfile.txt"); | |
assertThat(myFile.exists(), is(true)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment