3 回答

TA贡献1891条经验 获得超3个赞
您需要在写入之前确保父目录存在。您可以通过执行此操作File#mkdirs()。
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...

TA贡献1824条经验 获得超6个赞
随着Java 7中,你可以使用Path,Paths以及Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
添加回答
举报