[英]BufferedReader reads only once
我正在嘗試讀取配置文件和字符串文件。 配置文件將用於確定字符串文件中的內容是否正確。
我創建了一個名為StringAcceptor的程序包,部分代碼如下:
public static boolean isAccepted(File config, File lines_file, String string) throws Exception {
//BufferedReader para obtener las líneas del archivo
conf = new BufferedReader(new FileReader(config));
//BufferedReader para determinar la cantidad de líneas en el archivo
lines = new BufferedReader(new FileReader(lines_file));
//Validación de archivo de configuración del AFD
while(lines.ready()){
lines.readLine();
line_number = line_number + 1;
}
while(conf.ready()){
try{
在這里,我開始閱讀各行,並將值分配給相應的變量
然后,我創建了一個Java文件來使用該程序包,並將信息發送到我的StringAcceptor,以確定是否接受該字符串。 來自使用該程序包的類的代碼如下。 導入所需的軟件包並確定選項后,它將執行以下兩個選項之一:
case 1:
System.out.print("\nInsert configuration file name: ");
path = br.readLine();
archivo = new File(path);
if(archivo.isFile()){
System.out.print("\nInsert string to be verified: ");
String string = br.readLine();
if(StringAcceptor.isAccepted(archivo, archivo, string)){
System.out.println("\nAccepted!\n");
} else{
System.out.println("\nNot accepted.\n");
}
} else {
System.out.println("\nFile does not exist.\n");
}
break;
case 2:
System.out.print("\nInsert configuration file name: ");
path = br.readLine();
archivo = new File(path);
if(archivo.isFile()){
System.out.print("\nInsert name of string file to be verified: ");
String string = br.readLine();
strings = new File(string);
if(strings.isFile()){
BufferedReader sfile = new BufferedReader(new FileReader(strings));
while(sfile.ready()){
if(StringAcceptor.isAccepted(archivo, archivo, sfile.readLine())){
System.out.println("\nAccepted!\n");
} else {
System.out.println("\nNot Accepted.\n");
}
}
} else{
System.out.println("\nFile does not exist.\n");
}
} else {
System.out.println("\nFile does not exist.\n");
}
//archivo.delete();
break;
case 3:
exit = true;
break;
default:
System.out.println("\nInvalid Option.\n");
每當我執行代碼時,都會顯示以下菜單:
1)驗證字符串2)驗證字符串文件3)退出插入選項:
現在,無論我先選擇哪個選項或先使用哪個配置文件,它都只會在第一次時正確執行,每次之后它都不會進入while(conf.ready())
有條件的狀態,就永遠不會讀取行,因此總是會返回false
。
希望我的編輯使其更易於理解。
擺脫所有ready()
測試。 將其用作流結束的測試是無效的。 那不是它的目的。 請參閱Javadoc。 一直讀取,直到readLine()
返回null為止:
while ((line = in.readLine()) != null)
好的,所以我發現我完全搞砸了。 我非常專注於正在閱讀的文件,因此我確定這是問題所在。 原來的問題是,我沒有將我用於幾個for
周期的一些int
“控制變量”初始化為0,所以我最終讀取的內容超出了我的預期for
因為我一直在添加變量的最后一個值(奇怪的是,它沒有顯示異常)。
盡管如此,還是感謝大家的幫助,如果我沒有根據您的建議更改代碼,就永遠不會知道發生了什么。
您應該刪除ready
方法。 在使用BufferedReader
讀取時,請使用readLine
方法檢查數據是否可用,然后繼續。
另外,在讀取文件時,我看不到關閉流的代碼。 例如下面的語句打開文件以供閱讀
BufferedReader sfile = new BufferedReader(new FileReader(strings));
但是對sfile.close()
的調用在sfile.close()
。 同樣,isAccepted方法也正在打開文件流,而根本沒有關閉它。
你最好用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.