標籤:
java7中輔助類Files新增了兩個方法用於讀去檔案的全部行和全部位元組。So..再也不用緩衝區了。
1 package java8_test; 2 3 import java.io.IOException; 4 import java.nio.file.Files; 5 import java.nio.file.Path; 6 import java.nio.file.Paths; 7 import java.util.List; 8 9 public class TestMain {10 11 public static void main(String[] args) {12 // TODO Auto-generated method stub13 Path logFile=Paths.get("/home/frank/java8" );14 List<String> lines;15 try {16 lines = Files.readAllLines(logFile);17 for(String str:lines){18 System.out.println(str);19 }20 } catch (IOException e) {21 // TODO Auto-generated catch block22 e.printStackTrace();23 }24 }25 26 27 }
該類也與以前的java I/O代碼相容
1 try { 2 Path logFile=Paths.get("/home/frank/java8" ); 3 BufferedReader reader=Files.newBufferedReader(logFile); 4 String line; 5 while((line=reader.readLine()) != null){ 6 System.out.println(line); 7 } 8 } catch (IOException e) { 9 // TODO Auto-generated catch block10 e.printStackTrace();11 }
java 7 使用java.nio.file.*操作檔案