多线程管道读写

2019-07-12  本文已影响0人  招风小妖怪
import java.io.*;

//源文件-->路径---》FileInputStream-->PipOutputStream---->PipInputStream--->FileOutPutStream--->路径---》目标文件
//1   目标文件的数据把数据读出来,到读的字节流,写到管道中
class ReadThread extends Thread
{
    String sourcePath;
    PipedOutputStream pos;
    
    ReadThread(String path,PipedOutputStream pos)
    {
        this.sourcePath=path;
        this.pos=pos;
    }
    
    public void run()
    {
        try
        {
            FileInputStream fis = new FileInputStream(sourcePath);
            int data;
            while((data=fis.read())!=-1)
            {
                pos.write(data);
                sleep(10);
                System.out.print((char)data);
            }
            fis.close();
            pos.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}



//2   把读管道的数据,交给写的字节流,写到文件中

class WriteThread extends Thread
{
    String destPath;
    PipedInputStream pis;
    
    WriteThread(String path,PipedInputStream pis)
    {
        this.destPath=path;
        this.pis=pis;
    }
    
    public void run()
    {
        try
        {
            FileOutputStream fos = new FileOutputStream(destPath);
            int data;
            while((data=pis.read())!=-1)
            {
                fos.write(data);
            }
            fos.close();
            pis.close();
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}



//3    主类,生成读写文件,2个管道,两个管道保证连接

class Demo05
{
    public static void main(String s[])throws Exception
    {
        String              sourcePath  = "Demo05.java";
        String              destPath    = "Demo05.txt";
        PipedInputStream    pis         = new PipedInputStream();
        PipedOutputStream   pos         = new PipedOutputStream();
        pis.connect(pos);
        
        ReadThread          readThread  = new ReadThread(sourcePath,pos);
        WriteThread         writeThread = new WriteThread(destPath,pis);
        readThread.start();
        writeThread.start();
              
    }
}
上一篇 下一篇

猜你喜欢

热点阅读