Thursday 28 July 2016

Java Tutorial : Java IO (FileReader constructor accepts file object)

myfile.txt
Peter is coming to India. 

FileReaderDemo.java
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/*
 * public FileReader(File file) throws
 *                   FileNotFoundException
 * 
 * Parameters: 
 * ----------
 * 
 * file - the File to read from
 */

public class FileReaderDemo
{

    public static void main(String[] args) throws IOException
    {
        FileReaderDemo fileReaderDemo = new FileReaderDemo();
        fileReaderDemo.readFile();
    }

    private void readFile() throws IOException
    {
        FileReader fileReader = null;

        try
        {
            File file = new File("myfile.txt");
            /*
             * Creates a new FileReader, given the File to
             * read from.
             */
            fileReader = new FileReader(file);
            int i;

            /*
             * Reads a single character or -1 if the end of
             * the stream has been reached
             */
            while ((i = fileReader.read()) != -1)
            {
                System.out.print((char) i);
            }
        }
        finally
        {
            if (fileReader != null)
            {
                /*
                 * Closes the stream and releases any system
                 * resources associated with it. Once the
                 * stream has been closed, further read(),
                 * ready(), mark(), reset(), or skip()
                 * invocations will throw an IOException.
                 * Closing a previously closed stream has no
                 * effect.
                 */
                fileReader.close();
            }
        }
    }
}
Output
Peter is coming to India. 

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_FileReader_Cons_File_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/JavaIODemo_FileReader_Cons_File_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/a5a29c88719d4853b7ba8bae1b5fc9715fbc328c/BasicJava/JavaIODemo_FileReader_Cons_File_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment