<tutorial title="Reading from a text file">
 <blurb>
  A program that processes a text file typically has the following stages:
  <ul>
   <li>Open the file for reading</li>
   <li>Loop until the file has been exhausted</li>
   <ul>
    <li>Read one line of text.</li>
    <li>Do something with that line.</li>
   </ul>
   <li>Close the file</li>
  </ul>
  A program with this structure will usually be more efficient than one that
  the entire file in one go.
 </blurb>
 <question className="Demo" title="Reading lines" copyFile='greeks.txt'>
  <blurb>
  <p>
  The text file <a target='doc' href="greeks.txt">greeks.txt</a>
  contains a single word on each line.
  </p>
  <p class='imper'>
  This program reads the file line by line and prints all the lines
  with four characters.
  </p>
  <p>
  Note that the end-of-line character is not
  included in the count.
  </p>
  </blurb>
 <blurb lang='java'>
  <ul>
   <li>The <code>BufferedReader</code> represents a text file that can process one
   line at a time.</li>
   <li>We need a <code>FileReader</code> to create the <code>BufferedReader</code>.</li>
   <li>We use the <code>readLine</code> method to obtain a single line of text.</li>
   <li>When the file has been exhausted the string returned will be <code>null</code>.</li>
  </ul>
 </blurb>
 <blurb lang='cs'>
  <ul>
   <li>The <code>StreamReader</code> represents a text file that can process one
   line at a time.</li>
   <li>We use the <code>ReadLine</code> method to obtain a single line of text.</li>
   <li>When the file has been exhausted the string returned will be <code>null</code>.</li>
  </ul>
 </blurb>
  <shell lang="java" className="Demo" import="shells.xml#null"/>
<prog lang="java"><![CDATA[
import java.io.BufferedReader;
import java.io.FileReader;
public class Demo{
  public static void main(String[] argv)
                        throws Exception{
    BufferedReader fh =
     new BufferedReader(new FileReader("greeks.txt"));
    String s;
    while ((s=fh.readLine())!=null)
      if (s.length()==4)
        System.out.println(s);
    fh.close();
  }
}
]]></prog>
<prog lang="cs"><![CDATA[
using System;
using System.IO;
public class Demo{
  public static void Main(string[] argv)
  {
    StreamReader fh = new StreamReader("greeks.txt");
    string s;
    while ((s=fh.ReadLine())!=null)
      if (s.Length==4)
        Console.WriteLine(s);
    fh.Close();
  }
}
]]></prog>
 </question>
</tutorial>

