Java7中NIO學習之建立新的檔案和資料夾
阿新 • • 發佈:2019-02-14
文章來源: http://evil850209.iteye.com/blog/1924446
public static void main(String[] args) { try { Path directoryPath = Paths.get("D:/home/sample"); Files.createDirectory(directoryPath); System.out.println("Directory created successfully!"); Path filePath = Paths.get("D:/home/sample/test.txt"); Files.createFile(filePath); System.out.println("File created successfully!"); Path directoriesPath = Paths.get("D:/home/sample/subtest/subsubtest"); System.out.println("Sub-directory created successfully!"); Files.createDirectories(directoriesPath); } catch (FileAlreadyExistsException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
在呼叫createFile方法時,如果想要建立的檔案已經存在,FileAlreadyExistsException會被丟擲。createFile和createDirectory這個兩個方法都是原子性的,即要不整個操作都能成功或者整個操作都失敗。