一、try_with_resources
try (Scanner in = new Scanner(Paths.get("F:/aaa.txt"));PrintWriter out = new PrintWriter("F:/temp.txt")){
while (in.hasNext())
out.print(in.next().toLowerCase());
}
這是try_with_resources的最簡潔形式,如果代碼塊中出現異常,都會調用close()方法,就像finally一樣。
二、Objects類
如果兩個字符串都爲null,則返回true,否則按照正常的equals方法比較,不存在空指針異常的問題。
String s1 = null;
String s2 = "";
boolean b = Objects.equals(s1, null);
System.out.println(b);
計算哈希碼、哈希值。
//null值返回0
Objects.hashCode(null);
Objects.hash(null);
//多個對象,哈希碼自動組合
int i = Objects.hash(null, "asa", 2);
檢測對象是否是null值,如果是null值,可以在異常輸出位置查看。
Objects.requireNonNull(null, "可以在異常輸出中看見位置");
三、比較數值
int i = Integer.compare(0, 1);
System.out.println(i);
int j = new Integer(1464616131234134).compareTo(46416);
System.out.println(j);
Integer.compare()比較兩個int數值;但是如果數值過大,可以使用new Integer().compareTo()來比較,會自動裝箱/拆箱兩個過大整數對象。結果是前者大於後者返回1,反之返回-1。
四、Path,Files使用
Path是一個含有多個或一個目錄名稱的序列,也可以帶文件名。
Path path = Paths.get("F:","/","test","/","aaa.txt");
path.getParent();//獲得上一級路徑
path.getRoot();//獲得根路徑
path.getFileName();//獲得文件名
path.getNameCount();//獲得目錄級數
Files類可以快速的實現一些常用的文件操作,快速的讀取文件的全部內容。
Path path = Paths.get("F:/aaa.txt");
//讀取爲字符串
byte[] bytes = Files.readAllBytes(path);
String string = new String(bytes, StandardCharsets.UTF_8);
//按照行讀取文件
List<String> list = Files.readAllLines(path, StandardCharsets.UTF_8);
System.out.println(list);
//反之寫入文件
Files.write(path, string.getBytes(StandardCharsets.UTF_8));
Files.write(path, list, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
還可以快速的寫入文件或讀取文件。
InputStream in = Files.newInputStream(path, StandardOpenOption.WRITE);
OutputStream out = Files.newOutputStream(path, StandardOpenOption.WRITE);
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, StandardOpenOption.WRITE);
複製、拷貝文件
//複製,還可以使用輸入輸出流
Files.copy(path, path2, StandardCopyOption.REPLACE_EXISTING);
//移動,重命名
Files.move(path, path2, StandardCopyOption.ATOMIC_MOVE);
//如果存在即刪除
Files.deleteIfExists(path);