Can I find the console width with Java?

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 …)

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.

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: 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.

Leave a Comment