1 Reply Latest reply: Jun 11, 2008 2:58 AM by 800282 RSS

    reading texts on a text file : something's missing

    807601
      hello guys,i have a hard time doing this program and i don't know what's missing.

      say i have a text file and it contains:

      yoho!
      yoho!
      yoho!

      the program should read all text in a file, but it just displays:

      yoho!
      null

      i wanna know what's the code in moving to the next line

      here's the code:

           
      public static void main (String args[])
           {
                
                FileInputStream fin;
                String opcTxt;
                int counter=0;
                
                try
                {
                    fin = new FileInputStream ("D:\\jf\\OperationClose\\opcdb.txt");
                    opcTxt="D:\\jf\\OperationClose\\opcdb.txt";
                    BufferedReader txtBuff = new BufferedReader(new FileReader(opcTxt));
                    while(txtBuff.readLine()!=null)
                    {
                         System.out.println(txtBuff.readLine());
                         counter++;
                    }
                    fin.close();
                    txtBuff.close();
                }
                catch (IOException e)
                {
                     System.err.println ("Unable to read from file");
                     System.exit(-1);
                }
        • 1. Re: reading texts on a text file : something's missing
          800282
          Aye, matey, you discard a couple of readLine()'s.
          while(txtBuff.readLine()!=null) // you read a line here and discard it!
          {
              System.out.println(txtBuff.readLine()); // and you read another line
              counter++;
          }
          So, you read and print all even line numbers, and discard all uneven ones.
          Do this instead:
          String line = "";
          while((line = txtBuff.readLine()) != null)
          {
              System.out.println(line); 
              counter++;
          }