我們知道在JDK6甚至之前的時候,我們想要讀取一個文本文件也是非常麻煩的一件事,而現在他們都變得簡單了, 這要歸功於NIO2,我們先看看之前的做法:
讀取一個文本文件
BufferedReader br = null; try { new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } catch (Exception e){ e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } }
大家對這樣的一段代碼一定不陌生,但這樣太繁瑣了,我只想讀取一個文本文件,要寫這么多代碼還要 處理讓人頭大的一堆異常,怪不得別人吐槽Java臃腫,是在下輸了。。。
下面我要介紹在JDK7中是如何改善這些問題的。
Path
Path用於來表示文件路徑和文件,和File對象類似,Path對象並不一定要對應一個實際存在的文件, 它只是一個路徑的抽象序列。
要創建一個Path對象有多種方法,首先是final類Paths的兩個static方法,如何從一個路徑字符串來構造Path對象:
Path path1 = Paths.get("/home/biezhi", "a.txt");
Path path2 = Paths.get("/home/biezhi/a.txt");
URI u = URI.create("file:////home/biezhi/a.txt");
Path pathURI = Paths.get(u);
通過FileSystems構造
Path filePath = FileSystems.getDefault().getPath("/home/biezhi", "a.txt");
Path、URI、File之間的轉換
File file = new File("/home/biezhi/a.txt"); Path p1 = file.toPath(); p1.toFile(); file.toURI();
讀寫文件
你可以使用Files類快速實現文件操作,例如讀取文件內容:
byte[] data = Files.readAllBytes(Paths.get("/home/biezhi/a.txt")); String content = new String(data, StandardCharsets.UTF_8);
如果希望按照行讀取文件,可以調用
List<String> lines = Files.readAllLines(Paths.get("/home/biezhi/a.txt"));
反之你想將字符串寫入到文件可以調用
Files.write(Paths.get("/home/biezhi/b.txt"), "Hello JDK7!".getBytes());
你也可以按照行寫入文件,Files.write方法的參數中支持傳遞一個實現Iterable接口的類實例。 將內容追加到指定文件可以使用write方法的第三個參數OpenOption:
Files.write(Paths.get("/home/biezhi/b.txt"), "Hello JDK7!".getBytes(),
StandardOpenOption.APPEND);
默認情況Files類中的所有方法都會使用UTF-8編碼進行操作,當你不願意這么干的時候可以傳遞Charset參數進去變更。
當然Files還有一些其他的常用方法:
InputStream ins = Files.newInputStream(path); OutputStream ops = Files.newOutputStream(path); Reader reader = Files.newBufferedReader(path); Writer writer = Files.newBufferedWriter(path);
創建、移動、刪除
創建文件、目錄
if (!Files.exists(path)) { Files.createFile(path); Files.createDirectory(path); }
Files還提供了一些方法讓我們創建臨時文件/臨時目錄:
Files.createTempFile(dir, prefix, suffix);
Files.createTempFile(prefix, suffix);
Files.createTempDirectory(dir, prefix);
Files.createTempDirectory(prefix);
這里的dir是一個Path對象,並且字符串prefix和suffix都可能為null。 例如調用Files.createTempFile(null, “.txt”)會返回一個類似/tmp/21238719283331124678.txt
讀取一個目錄下的文件請使用Files.list和Files.walk方法
復制、移動一個文件內容到某個路徑
Files.copy(in, path);
Files.move(path, path);
刪除一個文件
Files.delete(path);
