You can use named pipes
to redirect your logs from your java application to a named pipe. And in your another java application you should read the content from the named pipe.
Named pipe definition:
A FIFO, also known as a named pipe, is a special file similar to a pipe but with a name on the filesystem. Multiple processes can access this special file for reading and writing like any ordinary file.
Here is an example:
Creating the named pipe:
mkfifo /home/user/pipe1
Java Application that shows the logs
Assuming that you have this application:
Main.java
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("Hello From Java!");
Thread.sleep(5000); //sleep 5 seconds
System.out.println("Goodbye");
}
}
And the another java application which read the logs from Main.java
ReadLogs.java
import java.io.*;
public class ReadLogs {
static BufferedReader pipeReader;
public static void createBuffer(String namedPipe) throws Exception {
pipeReader = new BufferedReader(new FileReader(new File(namedPipe)));
}
public static void process() throws Exception {
String msg;
while ((msg = pipeReader.readLine()) != null) {
System.out.println("Message: "+msg);
}
}
public static void main(String args[]) throws Exception {
createBuffer("/home/user/pipe1");
process();
System.out.println("EOF: Finished");
}
}
Redirecting the logs from your java application to named pipe:
java MainApplication > /home/user/pipe1
Finally you will have to read the content of the named pipe running the ReadLogs java application:
java ReadLogs
Note: The Main.java application will redirect each output to the pipe1
only if the content of this one has been read.
For example, if you only run java Main > /home/user/pipe1
the program will wait for a process that read the content of pipe1
.
You can try the following code for reading pipe1
without using java:
#In the terminal type:
java MainApplication > /home/user/pipe1
#In another terminal or tab:
cat /home/user/pipe1