Question

I have a java program in a UNIX environment which requires line buffered data to be passed into System.in.

Passing in keyboard input from the terminal is fine, however if I try to redirect the input from a file in a way such as:

java the_program < input.txt

the program will not execute properly.

In what ways can I have line buffered as opposed to block buffered data be passed into the program via stdin?

I have tried:

stdbuf -oL cat input.txt | java the_program

and

stdbuf -i0 java the_program < input.txt

as well as

grep --line-buffered . input.txt | java the_program

but have not had any luck.

Any ideas or suggestions?

Was it helpful?

Solution

Most of the problem is in the Java program - why/how does it need the input to be line-buffered? It should be designed to use the analogue of C's fgets() so that it just reads a line at a time. If there is no such analogue, then maybe you need to write a function/class that provides that service, taking whatever you can read in whatever units are provided, and either split or concatenate at line boundaries.

Failing that, you may have to indulge in unportable operations such as using the fstat() system call on the pipe file descriptor, only writing to the pipe when there is no data in it (looking at the st_size member). However, it is not guaranteed that it will work - unportable means it may not. Obviously, you'd ensure your program writes a line at a time and flushes the output if using standard I/O.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top