Java 8 讀取文件

之前的Java版本中讀取文件很是繁瑣,如今比較簡單。使用Java8的Files以及Lambda,幾句代碼就能夠搞定。windows

 

public static String getXml() {
StringBuffer xml = new StringBuffer();
Path path = Paths.get("C:\\Users\\Administrator\\Desktop\\xml.txt");
try {
List<String> lines = Files.readAllLines(path);
lines.forEach(str -> xml.append(str));
} catch (IOException e) {
e.printStackTrace();
}
return xml.toString();
}app

 

若是遇到提示說「前言中不容許有內容」,請把XML保存爲無BOM頭的UTF-8。windows記事本默認是有BOM頭的,是爲了給操做系統檢測編碼使用的,請使用UE修改。編碼

相關文章
相關標籤/搜索