如何将行缓冲数据从文件重定向到程序而不是块缓冲数据

发布于 2024-10-03 23:45:12 字数 511 浏览 0 评论 0原文

我在 UNIX 环境中有一个 java 程序,需要将行缓冲数据传递到 System.in 中。

从终端传递键盘输入很好,但是如果我尝试以以下方式重定向文件中的输入:

java the_program < input.txt

程序将无法正确执行。

我可以通过哪些方式将行缓冲数据(而不是块缓冲数据)通过标准输入传递到程序中?

我已经尝试过:

stdbuf -oL cat input.txt | java the_program

以及

stdbuf -i0 java the_program < input.txt

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

但没有任何运气。

有什么想法或建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫罗兰の梦幻 2024-10-10 23:45:12

大多数问题出在 Java 程序中——为什么/如何需要对输入进行行缓冲?它应该被设计为使用 C 的 fgets() 的类似物,以便它一次只读取一行。如果没有这样的类似物,那么也许您需要编写一个提供该服务的函数/类,采用您可以在提供的任何单元中读取的任何内容,并在行边界处拆分或连接。

如果做不到这一点,您可能不得不沉迷于不可移植的操作,例如在管道文件描述符上使用 fstat() 系统调用,仅在管道中没有数据时写入管道(查看 <代码>st_size成员)。然而,并不能保证它一定能工作——不可移植意味着它可能不会。显然,如果使用标准 I/O,您需要确保您的程序一次写入一行并刷新输出。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文