Can I find the console width with Java?
Actually, a Java library already exists to do this in Java: JLine 2. (There's an old version on SourceForce, but that link to GitHub seems to be the latest.)
This worked for me under Linux (Mint 14) and Windows (I don't know what version), using JLine 2.11:
terminalWidth = jline.TerminalFactory.get().getWidth();
JLine promises to work on Mac, too.
I've found that it returns bad widths (like 1
!) under the Eclipse console (but even Java's native Console doesn't work under Eclipse!), and, unfortunately, under Cygwin. But I've worked around this with code that checks for unreasonable values (< 10
) and just uses 80 in those cases.
Update for JLine 3 (per Mark—thanks, mate!):
terminalWidth = org.jline.terminal.TerminalBuilder.terminal().getWidth()
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.