我(想)我正在逐行处理文本文件,直到找到特定的标记;
(Psuedo Code)
Scanner scanner = new Scanner(new FileReader("myTextFile.txt");
while (scanner.hasNext() {
boolean found = process(scanner.nextLine();
if (found) return;
}
有些文件很庞大。这段代码是否实际上逐行扫描文件,或者Scanner或FileReader是否将整个文件读入内存,然后逐行通过内存缓冲区工作?
答案 0 :(得分:3)
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
boolean found = false;
while ((line = br.readLine()) != null) {
if(line.equalsIgnoreCase("Your string"))
found = true;
}
答案 1 :(得分:1)
public static void main(String[] args) {
File file = new File("C:\\testing.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
System.out.println(dis.readLine());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
bis.close();
dis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
答案 2 :(得分:0)
Path filePath = Paths.get("myTextFile.txt");
boolean found = false;
try (BufferedReader br = Files.newBufferedReader(filePath, CharSet.forName(<char-set-name>)){
for (String line = br.readLine(); line != null; line = br.readLine()) {
found = process(line);
if (found){
break;
};
}
}