Skip to content

Instantly share code, notes, and snippets.

@tblachowicz
Created February 13, 2012 12:36
Show Gist options
  • Save tblachowicz/1816555 to your computer and use it in GitHub Desktop.
Save tblachowicz/1816555 to your computer and use it in GitHub Desktop.
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;
}
}
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