Feb 13, 2010

How do I read a text file?

How do I read a text file?

The code shown below is an example how to read a text file. This program will read a file called test.txt and shown its content.

=====================================
Publicize yourself ... Free!
http://saalram.com
=====================================

01.import java.io.BufferedReader;
02.import java.io.File;
03.import java.io.FileReader;
04.import java.io.FileNotFoundException;
05.import java.io.IOException;
06. 
07.public class ReadTextFileExample
08.{
09.    public static void main(String[] args)
10.    {
11.        File file = new File("test.txt");
12.        StringBuffer contents = new StringBuffer();
13.        BufferedReader reader = null;
14. 
15.        try
16.        {
17.            reader = new BufferedReader(new FileReader(file));
18.            String text = null;
19. 
20.            // repeat until all lines is read
21.            while ((text = reader.readLine()) != null)
22.            {
23.                contents.append(text)
24.                    .append(System.getProperty(
25.                        "line.separator"));
26.            }
27.        } catch (FileNotFoundException e)
28.        {
29.            e.printStackTrace();
30.        } catch (IOException e)
31.        {
32.            e.printStackTrace();
33.        } finally
34.        {
35.            try
36.            {
37.                if (reader != null)
38.                {
39.                    reader.close();
40.                }
41.            } catch (IOException e)
42.            {
43.                e.printStackTrace();
44.            }
45.        }
46.         
47.        // show file contents here
48.        System.out.println(contents.toString());
49.    }
50.}

=====================================
Publicize yourself ... Free!
http://saalram.com
=====================================


No comments:

 
Saalram
Publicize yourself ...
http://saalram.com

Free !!!


Place your Ad here - Free!!!
just drop us a mail ... saalram.service@gmail.com

Free !!!