我有条件在继续(./logs/error.log
)之前检查是否存在某个文件。如果找不到,我要创建它。但是,会
File tmp = new File("logs/error.log");
tmp.createNewFile();
还创建logs/
它是否不存在?
Answers:
Java 8样式
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
写入文件
Files.write(path, "Log log".getBytes());
读书
System.out.println(Files.readAllLines(path));
完整的例子
public class CreateFolderAndWrite {
public static void main(String[] args) {
try {
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Files.write(path, "Log log".getBytes());
System.out.println(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}