Difference between revisions of "Read a Text File"

From Progzoo
Jump to: navigation, search
Line 26: Line 26:
 
some lines of text.
 
some lines of text.
 
</p>
 
</p>
 +
</question>
 +
 +
<question>
 +
You can use the try feature in Java 7. This ensures that the file will be closed and disposed of even if the read fails.
 +
<def>
 +
import java.io.BufferedReader;
 +
import java.io.FileReader;
 +
public class Demo{
 +
  public static void main(String[] argv)
 +
                        throws Exception{
 +
    try(BufferedReader br =
 +
      new BufferedReader(new FileReader("haggis.txt")))
 +
    {
 +
      for(String line = br.readLine();line!=null;line=br.readLine())
 +
        System.out.println(line);
 +
    }
 +
  }
 +
}
 +
</def>
 
</question>
 
</question>

Revision as of 09:02, 27 September 2015

You can open a text file and read each line.
  • The BufferedReader represents a text file.
  • You can create BufferedReader from an

FileReader.

  • The while condition (s=fh.readLine())!=null does two

things, it assigns the string s and it checks for null.

The text file [haggis.txt] includes some lines of text.

[Font] [Default] [Show] [Resize] [History] [Profile]

You can use the try feature in Java 7. This ensures that the file will be closed and disposed of even if the read fails. <def> import java.io.BufferedReader; import java.io.FileReader; public class Demo{

 public static void main(String[] argv)
                       throws Exception{
   try(BufferedReader br =
      new BufferedReader(new FileReader("haggis.txt")))
   {
     for(String line = br.readLine();line!=null;line=br.readLine())
        System.out.println(line);
   }
 }

} </def>

[Font] [Default] [Show] [Resize] [History] [Profile]