我可以用 Java 找到控制台宽度吗?

2022-01-11 00:00:00 console java

有没有办法找到运行我的 Java 程序的控制台的宽度?

Is there a way to find the width of the console in which my Java program is running?

如果可能的话,我希望这是跨平台的......

I would like this to be cross platform if possible...

我不想更改缓冲区或窗口的宽度,我只想知道它的宽度,以便正确格式化正在打印到屏幕上的文本.

I have no desire to change the width of the buffer or the window, I just want to know its width so I can properly format text that is being printed to screen.

推荐答案

对于这个问题没有可靠的跨平台解决方案.确实,在某些情况下无法知道真正的控制台宽度是多少.

There are no reliable cross-platform solutions to this problem. Indeed, there are situations where it is not possible to know what the real console width is.

(请参阅其他答案以了解在某些时间和/或在某些平台上有效的方法.但请注意限制...)

(See other answers for approaches that work some of the time and/or on some platforms. But beware of the limitations ...)

例如,在 Linux 系统上,您通常可以从 LINES 和 COLUMNS 环境变量中找出名义终端尺寸.当您调整某些终端仿真器"的大小时,这些变量会自动更新;窗户,情况并非总是如此.实际上,在通过 telnet 协议连接的远程控制台的情况下,无法将实际终端尺寸获取到用户的 shell.

For example, on a Linux system you can typically find out the notional terminal dimensions from the LINES and COLUMNS environment variables. While these variables are automatically updated when you resize some "terminal emulator" windows, this is not always the case. Indeed, in the case of a remote console connected via telnet protocol, there is no way to get the actual terminal dimensions to the user's shell.

编辑:只是补充一点,如果用户在启动 Java 应用程序后在 Linux 上更改了他/她的 xterm 的尺寸,Java 应用程序将不会收到通知,也不会看到新维度反映在其 LINESCOLUMNS 环境变量的副本中!

EDIT: Just to add that if the user changes the dimensions of his/her xterm on Linux after launching a Java app, the Java app won't be notified, and it won't see the new dimensions reflected in its copy of the LINES and COLUMNS environment variables!

EDIT 2:我的错误:LINESCOLUMNSbash shell 变量,它们没有被导出默认为环境.你可以修复"在运行 Java 应用程序之前运行 export COLUMNS LINES.

EDIT 2: My mistake: LINES and COLUMNS are bash shell variables, and they are not exported to the environment by default. You can "fix" this by running export COLUMNS LINES before you run your Java application.

相关文章