Monday, 19 September 2016

Java Tutorial : Java IO (PipedInputStream and PipedOutputStream-V2)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=MCmiVH-BlN8&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java IO (PipedInputStream and PipedOutputStream-V2) 
PipedReadWriteDemo.java
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/*
 * Here, we have created two threads thread1 and
 * thread2. The thread1 thread writes the data using the
 * PipedOutputStream object and the thread2 thread reads
 * the data from that pipe using the PipedInputStream
 * object. Both the piped stream object are connected
 * with each other.
 */

public class PipedReadWriteDemo
{

    public static void main(String[] args) throws IOException
    {

        final PipedOutputStream pos = new PipedOutputStream();
        final PipedInputStream pis = new PipedInputStream(pos);

        Thread thread1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    String str = "Hello peter, Welcome to india.";
                    byte[] byteArray = str.getBytes();
                    pos.write(byteArray);
                    Thread.sleep(1000);
                    pos.close();
                }
                catch (Exception exe)
                {
                    exe.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    int data = pis.read();
                    while (data != -1)
                    {
                        System.out.print((char) data);
                        data = pis.read();
                    }
                    pis.close();
                }
                catch (Exception exe)
                {
                    exe.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
Output
Hello peter, Welcome to india.
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/JavaIODemo_Pipes_App.zip?attredirects=0&d=1

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/301d989d72a8b053f20342cfe0bd4a5c143c23aa/BasicJava/JavaIODemo_Pipes_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

    Google+ Followers

    Google+ Badge