JAVA IO - 从文件中读取数据的6种方法
// 1.Scanner
@Test
void testReadFile1() throws IOException {
//文件内容:Hello World|Hello Zimug
String fileName = "D:\data\test\newFile4.txt";
try (Scanner sc = new Scanner(new FileReader(fileName))) {
while (sc.hasNextLine()) { //按行读取字符串
String line = sc.nextLine();
System.out.println(line);
}
}
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\|"); //分隔符
while (sc.hasNext()) { //按分隔符读取字符串
String str = sc.next();
System.out.println(str);
}
}
//sc.hasNextInt() 、hasNextFloat() 、基础数据类型等等等等。
//文件内容:1|2
fileName = "D:\data\test\newFile5.txt";
try (Scanner sc = new Scanner(new FileReader(fileName))) {
sc.useDelimiter("\|"); //分隔符
while (sc.hasNextInt()) { //按分隔符读取Int
int intValue = sc.nextInt();
System.out.println(intValue);
}
}
}
// 2.Files.lines
@Test
void testReadFile2() throws IOException {
String fileName = "D:\data\test\newFile.txt";
// 读取文件内容到Stream流中,按行读取
Stream<String> lines = Files.lines(Paths.get(fileName));
// 按文件行顺序进行处理
//lines.forEachOrdered(System.out::println);
// 按文件行顺序进行处理
//lines.parallel().forEachOrdered(System.out::println);
// 转换成List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
//List<String> collect = lines.collect(Collectors.toList());
// 随机行顺序进行数据处理
lines.forEach(ele -> {
System.out.println(ele);
});
}
// 3.Files.readAllLines
@Test
void testReadFile3() throws IOException {
String fileName = "D:\data\test\newFile3.txt";
// 转换成List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
List<String> lines = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
lines.forEach(System.out::println);
}
// 4.Files.readString(JDK 11)
@Test
void testReadFile4() throws IOException {
String fileName = "D:\data\test\newFile3.txt";
// java 11 开始提供的方法,读取文件不能超过2G,与你的内存息息相关
//String s = Files.readString(Paths.get(fileName));
}
// 5.Files.readAllBytes()
@Test
void testReadFile5() throws IOException {
String fileName = "D:\data\test\newFile3.txt";
//如果是JDK11用上面的方法,如果不是用这个方法也很容易
byte[] bytes = Files.readAllBytes(Paths.get(fileName));
String content = new String(bytes, StandardCharsets.UTF_8);
System.out.println(content);
}
// 6.经典管道流的方式
@Test
void testReadFile6() throws IOException {
String fileName = "D:\data\test\newFile3.txt";
// 带缓冲的流读取,默认缓冲区8k
try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
//java 8中这样写也可以
try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))){
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
/*try (FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis)){
ois.readObject();
} */