全部博文(626)
分类: Java
2015-03-02 20:39:47
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class FileReadingTest { public static void main(String[] args) throws IOException { // Java 7 例子 // Files.readAllBytes默认以UTF-8编码读入文件,故文件的编码如果不是UTF-8,那么中文内容会出现乱字符 System.out.println(new String(Files.readAllBytes(Paths.get("D:\\jd.txt")))); // Java 8例子 Listlines = Files.readAllLines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); for(String line : lines){ sb.append(line); } String fromFile = sb.toString(); System.out.println(fromFile); } }
import static java.lang.System.out; import static java.nio.file.Files.readAllBytes; import static java.nio.file.Paths.get; import java.io.IOException; public class FileIntoString { public static void main(String[] args) throws IOException { // 一行代码搞定读文件,默认是UTF-8编码 out.println(new String(readAllBytes(get("d:/jd.txt")))); } }
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class Java8FileReader { public static void main(String[] args) throws IOException { // Java8用流的方式读文件,更加高效 Files.lines(Paths.get("D:\\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println); } }