Sunday, 29 July 2018

Reading and Writing Files using StreamReader in C#


Reading and writing files is an important for any program. C# has provided many classes to perform operations on Files.
Below is the Program showing use of StreamReader and StreamWriter to write the Characters in the Files.

using System;
using System.IO;
using static System.Console;
namespace StreamDemo
{
class Program
{
static string line="";
static void Main(string[] args)
{
StreamWriter st = new StreamWriter("D:\\Test.txt",true);
string [] cars = { "Audi", "Jeep","Jaguar" };
foreach(string s in cars)
{
st.WriteLine(s);
}
st.Close();
StreamReader sr = new StreamReader("D:\\Test.txt");
while ((line = sr.ReadLine()) != null)
{
WriteLine(line);
}
sr.Close(); ReadLine();
}
}
}


Output

Explanation
  • Above Program writes the array of cars in the File character by character.
  • StreamReader and StreamWriter performs the operations on files character by characters.
  • We initialized the object of StreamWriter class and gave the path where the file is to be created.
  • If the files with the same name is already present there at the path, StreamWriter opens that file.
  • If the file at the given path has already some text , and the append property is set to true, the StreamWriter class will append the text at the end of existing text.
  • using foreach loop , we write the array of string is the file.
  • Then we close the connection of the StreamWriter to the file
  • Closing the open connection is necessary , otherwise you will not able to access that file with StreamReader. It will throw an error that file is already in use.
  • Then using the StreamReader object , we access that file.
  • Using While loop we read the containts of the file and display it on the console.


  • Let's do the same program in different way.
    using System;
    using System.IO;
    using static System.Console;
    namespace FileApplication
    {
    class Program
    {
    static void Main(string[] args)
    {
    string[] names = new string[5];
    WriteLine("Enter names of fruits");
    for (int i = 0; i < names.Length; i++)
    {
    names[i] = ReadLine();
    }
    using (StreamWriter sw = new StreamWriter("D:\\names2.txt"))
    {
    WriteLine("Fruit names are below");
    foreach (string s in names)
    {
    sw.WriteLine(s);
    }
    }
    // Read and show each line from the file.
    string line = "";
    using (StreamReader sr = new StreamReader("D:\\names2.txt"))
    {
    while ((line = sr.ReadLine()) != null)
    {
    WriteLine(line);
    }
    }
    ReadKey();
    }
    }
    }


    Output

    Explanation
  • In above program , we are taking user input in the array of strings and writing in the file at the given path.
  • We have not specified if the append is true or false, so by default it is false.
  • Here we have used the statement using so that the connection is automatically close with the close of using statement.
  • the program ask user for name 5 fruits and writes in the file and also displays on the console.
  • Sunday, 15 July 2018

    Interface in C#


    interface is an another aspect of object oriented programming. An interface contains the declaration of properties,methods ,events. To implement these methods , a class must implement interface and define the methods in the interface. An interface is useful in a scenarios where there are multiple class that needs to have the same methods/functions. In this case , an interface can be defined containing only the method declaration and rest is the responsibility of the class to implement the interface and the methods according to class functionality.

    A class can implement multiple interfaces. If a class implements an interface, It must implement all the methods declared in interface.

    An Interface declaration is similar to class declaration. To declare an interface , interface keyword is used.

    Syntax

    public interface IAnimal {
    void run();
    void hunt();
    }


    Implementing Interface

    Class c1:interface_name
    {
    }


    Example

    using System;
    namespace InterfaceDemo
    {
    public interface Operations
    {
    void buyItems(string s1,string s2);
    int showAmount();
    }
    }


    Class Implementing interface.

    using System;
    namespace InterfaceDemo
    {
    public class ItemsList : Operations
    {
    private string item1;
    private string item2;
    private int amt;
    public ItemsList(int a)
    {
    amt = a;
    }
    public void buyItems(string sI1,string sI2)
    {
    item1 = sI1;
    item2 = sI2;
    Console.WriteLine("Items to buy \" {0}\" , \"{1}\"", item1, item2);
    }
    public int showAmount()
    {
    return amt;
    }
    }
    }


    Main Class

    using System;
    namespace InterfaceDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    ItemsList i = new ItemsList(2000);
    i.buyItems("Cooler", "Sofa");
    int k=i.showAmount();
    Console.WriteLine("Amount to be given is {0}", k);
    Console.ReadKey();
    }
    }
    }


    Explanation

  • First we created an class file and declared an interface in it named operation
  • We declared two methods in this one with two parameters and other with return type.
  • Then we created as class called as ItemsList and implemented the interface operation.
  • We implemented both the methods defined in the interface in the class ItemsList
  • Finally in the main class , we created an object of ItemsList class and called the two methods.


  • Note- A class has to implement all the methods defined in the interface. Other wise program will throw an error.

    Output

    Sunday, 8 July 2018

    Program showing creating, reading and writing files in Java


    Files also plays important role in any program. For example , if a program needs a log file to be used for storing the records of all the operations performed , then we can create a file and store at some location so that we can track activities performed by that program.

    Java contains a package named Java.io is having multiple classes that are used to perform input output operation of Files.

    Stream- a Stream is nothing but a sequence of data.There are two Streams in Java.

    Inputstream - to data from Files.

    Outputstreams- to write data in Files. Basically there are 3 streams in Java.

    Byte Stream- performs I/O of 8 bit bytes.
    Character Stream- used to perform input output on 16 bit Unicode characters.
    Standard Stream

    Byte Stream
    The following program shows how to read and write bytes using two classes. FileInputStream and FileOutputStream.

    package FilePackage;

    import java.io.IOException;
    import java.io.*;
    public class FileClass {
    public static void main(String[] args {
    FileInputStream fin=null;
    FileOutputStream fout=null;
    try
    {
    fin=new FileInputStream("D:/input.txt");
    fout=new FileOutputStream("D:/output.txt");
    int n;
    while((n=fin.read())!= -1)
    {
    fout.write(n);
    }
    }
    catch(IOException ex)
    {
    System.out.println("Exception occured " + ex.toString());
    }
    finally
    {
    if(fin!=null)
    {
    fin.close();
    }
    if(fout!=null)
    {
    fout.close();
    }
    }


    Explaination

  • FileInputStream and FileOutputStream are the two basic classes used for reading and writing bytes into files.
  • In above program, we created objects of FileInputStream and FileOutputStream classes and initialized them in try block with the file name provided to constructors.
  • Remember the File from which data needs to be read must be present at particular location. Otherwise program will throw FileNotFoundException
  • Then using while loop we read the input.txt file to the end and write the text into the output file.
  • We used catch block to handle the exception if occurred
  • In finally we closed the open connections to both the streams.



  • Character Stream

    The following program shows how to read and write characters using two classes. FileReader and FileWriter.

    package FilePackage;

    import java.io.IOException;
    import java.io.*;
    public class FileClass {
    public static void main(String[] args {
    FileReader fin=null;
    FileWriter fout=null;
    try
    {
    fr=new FileReader("D:/input.txt");
    fw=new FileWriter("D:/output.txt");
    int n;
    while((n=fr.read())!= -1)
    {
    fw.write(n);
    }
    }
    catch(IOException ex)
    {
    System.out.println("Exception occured " + ex.toString());
    }
    finally
    {
    if(fr!=null)
    {
    fr.close();
    }
    if(fw!=null)
    {
    fw.close();
    }
    }


    Explaination

  • FileReader and FileWriter are the two basic classes used for reading and writing characters into files.
  • In above program, we created objects of FileReader and FileWriter classes and initialized them in try block with the file name provided to constructors.
  • Remember the File from which data needs to be read must be present at particular location. Otherwise program will throw FileNotFoundException
  • Then using while loop we read the input.txt file to the end and write the text into the output file.
  • We used catch block to handle the exception if occurred
  • In finally we closed the open connections to both the streams.



  • Standard Streams

    Like other programming languages , Java also provides mechanism for Standard input , standard output and standard Error.

    Standard Input -Providing data to users program via standard input device i.e Keyboard.
    Standard output- Producing output data provided by input to the output device i.e monitor.
    Standard Error- Outout the Error data to the computer screen using the standard error stream.
    Below Program demonstrate the use of Standard Input.

    import java.io.*;
    public class ReadStream {
    public static void main(String args[]) {
    InputStreamReader cin = null;
    try {
    cin = new InputStreamReader(System.in);
    System.out.println("Enter the characters, press 'q' to quit.");
    char ch;
    do {
    ch = (char) cin.read();
    System.out.print(ch);
    } while(ch != 'q');
    catch(IOException ex) { System.out.println("Exception occurred" + ex.toString());
    }
    }finally {
    if (cin != null) {
    cin.close();
    }
    }
    }
    }


    Please write your comment below