[英]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.