Skip to content

Instantly share code, notes, and snippets.

@kimble
Created July 31, 2014 08:22
Show Gist options
  • Save kimble/8d09b35a68106f223a2d to your computer and use it in GitHub Desktop.
Save kimble/8d09b35a68106f223a2d to your computer and use it in GitHub Desktop.
Junit Rule for working with temporary files and directories (draft)
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.io.File;
import java.io.IOException;
/**
* @author Kim A. Betti
*/
public class TemporaryDirectory implements TestRule {
private volatile File dir;
private TemporaryDirectory(File dir) {
this.dir = dir;
}
public TemporaryDirectory() {
}
public File getDir() {
return dir;
}
public TemporaryFile touch(String filename) throws IOException {
File touched = new File(dir, filename);
Files.touch(touched);
return new TemporaryFile(touched);
}
public TemporaryDirectory mkdir(String name) {
File subDirectory = new File(dir, name);
if (subDirectory.mkdir()) {
return new TemporaryDirectory(subDirectory);
}
else {
throw new IllegalStateException("Unable to mkdir " + name);
}
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
dir = Files.createTempDir();
base.evaluate();
}
finally {
FileUtils.deleteDirectory(dir);
}
}
};
}
public static class TemporaryFile {
private final File file;
public TemporaryFile(File file) {
this.file = file;
}
public void append(String line) throws IOException {
Files.append(line, file, Charsets.UTF_8);
}
public File underlyingFile() {
return file;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment