Class SyncPipe

java.lang.Object
com.everdro1d.libs.io.SyncPipe
All Implemented Interfaces:
Runnable

public class SyncPipe extends Object implements Runnable
A utility class that facilitates the transfer of data between an InputStream and an OutputStream.

This class is designed to be used in scenarios where data needs to be piped from one stream to another, such as redirecting process output or handling inter-thread communication.

Usage: Create an instance of the class with the desired InputStream and OutputStream, and run it in a separate thread to handle the data transfer asynchronously.

Example implementation based on Utils.runCommand():

 ProcessBuilder pb = new ProcessBuilder(List.of("echo", "SyncPipe Example Text"));
 Process p;
 try {
     p = pb.start();
     new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
     try (Scanner scanner = new Scanner(p.getInputStream())) {
         while (scanner.hasNextLine()) {
             String line = scanner.nextLine();
             if (!line.isEmpty()) {
                 System.out.println(line);
             }
         }
     }
     p.waitFor();
     System.out.println(p.exitValue());
 } catch (Exception e) {
     e.printStackTrace(System.err);
 }
 
  • Constructor Details

    • SyncPipe

      public SyncPipe(InputStream iStream, OutputStream oStream)
      Constructs a SyncPipe instance with the specified InputStream and OutputStream.
      Parameters:
      iStream - the InputStream to read data from
      oStream - the OutputStream to write data to
  • Method Details

    • run

      public void run()
      Transfers data from the InputStream to the OutputStream.

      This method reads data in chunks using a buffer and writes it to the OutputStream. It runs in a loop until the InputStream is fully read.

      Any exceptions encountered during the process are logged to System.err.

      Specified by:
      run in interface Runnable