Java7語法新特性:html
前言,這是大部分的特性,但還有一些沒有寫進去,好比多核 並行計算的支持增強 fork join 框架;這方面並無真正寫過和了解。也就不寫進來了。
java
public String generate(String name, String gender) {
String title = "";
switch (gender) {
case "男":
title = name + " 先生";
break;
case "女":
title = name + " 女士";
break;
default:
title = name;
}
return title;
public void read(String filename) throws BaseException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex; //保存原始異常
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException == null) {
readException = ex;
}
}
}
if (readException != null) {
throw new BaseException(readException);
}
}
}
public void read(String filename) throws IOException {
FileInputStream input = null;
IOException readException = null;
try {
input = new FileInputStream(filename);
} catch (IOException ex) {
readException = ex;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException ex) {
if (readException != null) { //此處的區別
readException.addSuppressed(ex);
}
else {
readException = ex;
}
}
}
if (readException != null) {
throw readException;
}
}
}
public void testSequence() {
try {
Integer.parseInt("Hello");
}
catch (NumberFormatException | RuntimeException e) { //使用'|'分割,多個類型,一個對象e
}
}
public void read(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
StringBuilder builder = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
builder.append(line);
builder.append(String.format("%n"));
}
return builder.toString();
}
}
public void copyFile(String fromPath, String toPath) throws IOException { try ( InputStream input = new FileInputStream(fromPath); OutputStream output = new FileOutputStream(toPath) ) { byte[] buffer = new byte[8192]; int len = -1; while( (len=input.read(buffer))!=-1 ) { output.write(buffer, 0, len); } } }
public int sum(int... args) {
int result = 0;
for (int value : args) {
result += value;
}
return result;
}
對collections的支持 數據庫
Java代碼app
如今你還能夠:框架
2.自動資源管理socket
原來:優化
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
br.close();
}
如今:ui
3.對通用實例建立(diamond)的type引用進行了改進 spa
原來:code
Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
如今:
Map<String, List<String>> anagrams = new HashMap<>();
4.數值可加下劃線
6.二進制文字
int binary = 0b1001_1001;
異常catch能夠一次處理完而不像之前一層層的surround;