n0p*_*0pe 81 java directory io file
我有条件在继续(./logs/error.log
)之前检查某个文件是否存在.如果找不到,我想创建它.但是,会的
File tmp = new File("logs/error.log");
tmp.createNewFile();
Run Code Online (Sandbox Code Playgroud)
logs/
如果它不存在也会创建?
Eng*_*uad 20
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
Run Code Online (Sandbox Code Playgroud)
Jak*_*sel 14
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();
Run Code Online (Sandbox Code Playgroud)
如果目录已经存在,则不会发生任何事情,因此您不需要任何检查.
Java 8样式
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Run Code Online (Sandbox Code Playgroud)
写入文件
Files.write(path, "Log log".getBytes());
Run Code Online (Sandbox Code Playgroud)
阅读
System.out.println(Files.readAllLines(path));
Run Code Online (Sandbox Code Playgroud)
完整的例子
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)