Skip to main content

APIzation: Replication Package

[Q#634564][A#2605884] How to open a Windows named pipe from Java?

https://stackoverflow.com/q/634564

On our Linux system we use named pipes for interprocess communication (a producer and a consumer). In order to test the consumer (Java) code, I would like to implement (in Java) a dummy producer which writes to a named pipe which is connected to the consumer. Now the test should also work in the Windows development environment. Thus I would like to know how to create a named pipe in Windows from Java. In Linux I can use mkfifo (called using Runtime.exec() ), but how should I do this on Windows?

Answer

https://stackoverflow.com/a/2605884

Use Named Pipes to Communicate Between Java and .Net Processes Relevant part in the link

APIzation

try {
  // Connect to the pipe
  RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw");
  String echoText = "Hello word\n";
  // write to pipe
  pipe.write ( echoText.getBytes() );
  // read response
  String echoResponse = pipe.readLine();
  System.out.println("Response: " + echoResponse );
  pipe.close();
} catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
package com.stackoverflow.api;

import java.io.RandomAccessFile;

public class Human2605884 {

  public static void openWindowsNamedPipe() {
    try {
      // Connect to the pipe
      RandomAccessFile pipe = new RandomAccessFile(
        "\\\\.\\pipe\\testpipe",
        "rw"
      );
      String echoText = "Hello word\n";
      // write to pipe
      pipe.write(echoText.getBytes());
      // read response
      String echoResponse = pipe.readLine();
      System.out.println("Response: " + echoResponse);
      pipe.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

package com.stackoverflow.api;

import java.io.RandomAccessFile;

/**
 * How to open a Windows named pipe from Java?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/2605884">https://stackoverflow.com/a/2605884</a>
 */
public class APIzator2605884 {

  public static void openWindows(String echoText) throws Exception {
    try {
      // Connect to the pipe
      RandomAccessFile pipe = new RandomAccessFile(
        "\\\\.\\pipe\\testpipe",
        "rw"
      );
      // write to pipe
      pipe.write(echoText.getBytes());
      // read response
      String echoResponse = pipe.readLine();
      System.out.println("Response: " + echoResponse);
      pipe.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}