Interview Questions

Java - File Read/Write Operations

The below code sample describes the File Read and Write Operation.

1. File Read
Read all the contents from the File which exists in the same machine.
Create a File in "C:/Src.txt" with some content inside. Executing the below program will fetch all the contents and print in the console.

2. File Write
Write the contents in to the File.
Executing the below program will overwrite the File in "C:/Src.txt" with the content given in the sample program.

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.java.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * FileOperations describes File read and Write operations
 */

public class FileOperations
{
    //Main class for testing
    public static void main(String[] args)
    {
        //File Name
        String fileName = "C:/Src.txt";

        //Read operation
        System.out.println(readFile(fileName));

        //Write operation
        String outputContent = "File Updated with this content";
        writeFile(fileName, outputContent);
    }

    /**
     * Read contents from the file
     *
     * @param   fileName   Name of the File to be read  
     * @return Content of the File
     */

    public static String readFile(String fileName)
    {
        String fileContent = null;
        FileInputStream fis;
        try
        {
            fis = new FileInputStream(fileName);

            DataInputStream in = new DataInputStream(fis);
            StringBuffer sb = new StringBuffer();

            while (in.available() != 0)
            {
                sb.append(in.readLine());
                sb.append("\n");
            }
            fileContent = sb.toString();
        }
        catch (FileNotFoundException e)
        {
            System.err.println("Error: File doesn't exists");
        }
        catch (IOException e)
        {
            System.err.println("Error in reading file");
        }
        return fileContent;
    }

    /**
     * Write contents in to the file
     *
     * @param  fileName  File Name to be written
     * @param   content    Content of the File
     */

    public static void writeFile(String fileName, String content)
    {
        FileOutputStream fis;
        try
        {
            fis = new FileOutputStream(fileName);
            DataOutputStream in = new DataOutputStream(fis);
            in.write(content.getBytes());
        }
        catch (FileNotFoundException e)
        {
            System.err.println("Error: File doesn't exists");
        }
        catch (IOException e)
        {
            System.err.println("Error in reading file");
        }
    }
}