不读取文本文件中的第一行

时间:2014-10-15 11:09:11

标签: java arrays notepad++ bufferedreader notepad

我创建了这个方法来从文本文件中读取数据。我存储了从String数组中的BufferedReader中重新获取的所有数据。现在,当您想要读取特定数据时,必须将行号作为参数传递给方法。问题是我从第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

This is the Text File

5 个答案:

答案 0 :(得分:3)

你正在跳过这条线:

      while(data.readLine() != null){ // --> reading here
        for(int i=0; i<data1.length;i++){
            data1[i]=data.readLine();   //--> and here

答案 1 :(得分:0)

您需要更改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;
            }
        }
    }

答案 2 :(得分:0)

您正在通过第一次data.readLine()来电跳过第一行。

您可以像这样简化循环:

for (int i = 0; i < data1.length && ((readData = data.readLine()) != null); i++) {
    data1[i] = readData;
}

答案 3 :(得分:0)

您可以尝试这样做以避免在开头阅读两次:

  String aux = data.readLine();
  while(aux != null){
    for(int i=0; i<data1.length;i++){
        data1[i] = aux;

希望它有所帮助。

Clemencio Morales Lucas。

答案 4 :(得分:0)

这可能是一个迟到的反应,但也许可以帮助某人。

根据代码中遵循的步骤,您可以尝试将其作为解决方案:

int i=0;
while(data.ready()){
  data1[i++] = data.readLine();
}

ready()函数将告诉我们流是否可供读取。如果缓冲区不为空,或者基础字符流已准备就绪,则缓冲字符流就绪。

希望有帮助:)

相关问题