[英]Not reading the first line from a text file
我已經創建了此方法以從文本文件讀取數據。 我將所有從BufferedReader中檢索到的數據存儲在String數組中。 現在,當您想讀取特定數據時,必須將行號作為參數傳遞給該方法。 問題是我從第2行獲取數據,但無法從第1行獲取數據。我在嘗試讀取數據的位置附加了文本文件的屏幕截圖。
public String read(int num) throws IOException{
String readdata;
String[] data1=new String[20];
try {
FileReader read = new FileReader("E:\\TextFile.txt");
BufferedReader data = new BufferedReader(read);
while(data.readLine() != null){
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine();
if(data1[i] == null){
break;
}//if
}//for
}//while
}//try
catch (FileNotFoundException e) {
e.printStackTrace();
}//catch
finally{
data.close();
}//finally
readdata=data1[num];
return readdata;
}//read
您正在跳過這一行:
while(data.readLine() != null){ // --> reading here
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine(); //--> and here
您需要更改while
循環
String str="";
while((str=data.readLine()) != null){ // read the line
for(int i=0; i<data1.length;i++){
data1[i]=str; // and reuse it
if(data1[i] == null){
break;
}
}
}
您的代碼有什么問題? 您正在跳過第一行。
while(data.readLine() != null){ // already reads first line here
for(int i=0; i<data1.length;i++){
data1[i]=data.readLine(); // now you are reading from 2nd line
if(data1[i] == null){
break;
}
}
}
data.readLine()
您將通過第一個data.readLine()
調用跳過第一行。
您可以像這樣簡化循環:
for (int i = 0; i < data1.length && ((readData = data.readLine()) != null); i++) {
data1[i] = readData;
}
您可以嘗試這樣做以避免在開始時閱讀兩次:
String aux = data.readLine();
while(aux != null){
for(int i=0; i<data1.length;i++){
data1[i] = aux;
希望能幫助到你。
克萊門西奧·莫拉萊斯·盧卡斯。
這可能是一個較晚的響應,但可能可以幫助某人。
按照代碼中遵循的步驟,您可以嘗試以下解決方案:
int i=0;
while(data.ready()){
data1[i++] = data.readLine();
}
ready()函數將告訴我們該流是否可供讀取。 如果緩沖區不為空,或者基礎字符流已准備好,則緩沖的字符流已准備就緒。
希望有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.