Java 按行读取文件
Java 按行读取文件
1. 使用 Scanner 按行读取文件
import java.io.*;
import java.util.Scanner;
class ReadFileWithScanner {
public static void main(String[] args) throws FileNotFoundException {
InputStream stream = new FileInputStream("src/main/resources/test-data.txt");
//InputStream stream = ReadFileWithScanner.class.getClassLoader().getResourceAsStream("test-data.txt");
Scanner scanner = new Scanner(stream);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
}
2. 使用 BufferedReader 按行读取文件
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
class ReadFileWithBufferedReader {
public static void main(String[] args) throws IOException {
File file = new File("src/main/resources/test-data.txt");
//URL fileUrl = ReadFileWithBufferedReader.class.getClassLoader().getResource("test-data.txt");
//File file = new File(fileUrl.getFile());
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while (true) {
line = bufferedReader.readLine();
if (Objects.isNull(line)) {
break;
}
System.out.println(line);
}
}
}
3. 使用 RandomAccessFile 按行读取文件
虽然是 Random,实际是顺序按行读取的。文件读取完毕后,可以通过 randomAccessFile.seek(0);
重置指针,再次从头读取文件。
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Objects;
class ReadFileWithRandomAccessFile {
public static void main(String[] args) throws IOException, InterruptedException {
File file = new File("src/main/resources/test-data.txt");
//File file = new File(ReadFileWithRandomAccessFile.class.getClassLoader().getResource("test-data.txt").getFile());
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
String line;
while (true) {
line = randomAccessFile.readLine();
if (Objects.isNull(line)) {
break;
}
System.out.println(line);
}
}
}
3. 使用 readAllLines 按行读取文件
注意,这个方法会把所有内容读取到内存当中,适合文件小的情况。
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
class ReadFileWithReadAllLines {
public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException {
Path path = Paths.get("src/main/resources/test-data.txt");
//Path path = Paths.get(ReadFileWithReadAllLines.class.getClassLoader().getResource("test-data.txt").toURI());
List<String> lines = Files.readAllLines(path);
for (String line: lines) {
System.out.println(line);
}
}
}
下一篇: Kafka 命令大全
学习了。