I want to stop the blinking cursor while running a program in Java with a Java command in Ubuntu terminal. How can I do it?
Your Java program doesn't exactly have control of the terminal the user ran it from. My advice would be to have your program manage its own window which you can control.
But if you don't feel like doing that then one idea is that there are codes which some terminals listen for. This is very dependent on what terminal you are using but Linux seems to mostly adhere to a spec.
Ubuntu manpages even lists its codes here: http://manpages.ubuntu.com/manpages/focal/man4/console_codes.4.html
Under ECMA-48 Set Graphics Rendition section it says that ESC [ 25 m sets blink off
correction, as mentioned by VGR, this controls whether printed text blinks, not the cursor blink
So search for and try some different codes for your specific terminal and remember to actually run from your terminal as your IDE terminal isn't necessarily the same:
// \u001B is ESC
public static final String ESC = "\u001B";
public static final String HIDE_CURSOR = ESC + "[?25l";
public static void main(String[] args) throws IOException {
System.out.print(HIDE_CURSOR);
System.out.println("Where'd your cursor go??");
}
Related
This question already has answers here:
How to clear the console?
(14 answers)
Closed last year.
I'm curious to know how to clear the console in Windows. I tried a few command, but nothing works
Runtime.getRuntime().exec("cls");
This didn't work for me.
I'd like to know if there is any method to clear the terminal in Java or if there is an external library to do this.
The link in answer by #Olivier does work but unfortunately most suggestions use a sub-process cls or don't explain how to enable on Windows.
In latest Windows 10 you can use ANSI code support in Window Terminal, but not directly in CMD.EXE consoles. To enable for CMD.EXE add the registry key VirtualTerminalLevel mentioned in these answers for ANSI colours and then you can print the appropriate ANSI/VT codes directly without running a sub-process:
System.out.print("\033[2J\033[1;1H");
Or
System.out.print(ANSI.CLEAR_SCREEN+ANSI.position(1, 1));
where simple definition of ANSI codes is:
public class ANSI {
// Control Sequence Introducer:
public static String CSI = "\u001b[";
public static String CLEAR_SCREEN = CSI+"2J";
public static String position(int row, int col) {
return CSI+row+";"+col+"H";
}
}
Note that other terminals or such as those in IDEs may not support the above.
Well, here is the problem, I have started using VScode, and I can't read from console cyrillic characters.
My code:
import java.util.Scanner;
class App {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in, "UTF-8");
String word = input.nextLine();
System.out.println(word);
}
}
Now when I enter any cyrillic string it will print empty string back to me. If i write something like
System.out.println("Привет"); //cyrillic symbols
It will print "Привет", which is fine. So I am guessing it has something to do with reading the string rather than outputing it.
chcp command gives Active code page: 65001
I have tried setting encoding and without it, but it doesn't seem to work, is there something I missed?
Thanks in advance
I've tested the code on my machine and got the same result: nothing shown;
You can see, when run it in external Window PowerShell or Command Prompt, the result is different but still not shown correctly:
When we change the encode style to GBK(936), the cyrillic characters can be displayed correctly:
When it comes to changing integrated terminal encoding style in vscode and execute code again, it still shows nothing:
About these different results between external Command Prompt and integrated terminal in VS Code, I've put a github request. And I'm doing some research, if any useful imformation i get, i will update you.
I do have some serious troubles understanding the console in java. I am running Eclipse, and I wanted to write a small program which prompts a few text messages to the console and receives a few strings as input arguments from it. Problem is: When I run my program, it opens the command line window properly, but my outputs are only printed on the Eclipse-Console.
In some way, I do understand why this is the case. The Command Line Windows expects commands, and not just some kind of a string or something. But how do i manage to output my Strings into the Command Line Window and read Strings from it, and not just commands.
Or am I doing it the wrong way? Do I have to open another "Console" where all my messages will be prompted and from which i can read strings a user wrote?
This is the code i use to open a command line window on start:
public static void main(String args[]) throws Exception {
Process process = new ProcessBuilder(new String[] { "cmd", "/C",
"start", "cmd" }).start();
System.out.println(process.waitFor());
Edit: I did still not manage to get this to working. Somehow, when I compiled the program, and I run it, it properly opens a command window, but no messages are posted there. Seems like "System.out.println("xxx") does not have any effect on this window.
There's no "console" specified by your program, but an stdin, stdout and stderr for input, output and error output. When you run your program from windows, these streams are bound to a command window, and if you run it in eclipse, they will be associated to the eclipse console. To give a more obscure example, ff you were running it through ssh, the streams would be associated to ssh, and ssh associated to your command window, and so on.
So, you're not doing anything wrong, you just need to run the program from the command line if you want stdout and stdin to come from that command window.
How do you open a command window, by the way?
You might want to read through this page:
http://pages.cs.wisc.edu/~hasti/cs368/JavaTutorial/NOTES/JavaIO_Scanner.html
Basically what you need to is create the input stream, tell the user to input something, and then get the input. E.g.
private static Scanner newScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Put your input here: ");
String inputValue = newScanner.nextLine();
System.out.println(inputValue);
}
Just remember to import the scanner library!
I am working on a game that involves clearing the screen after each turn for readability. The only problem is I cannot use the Windows command prompt-based "cls" command and it does not support ANSI escape characters. I used Dyndrilliac's solution on the following page but it resulted in an IOException:
Java: Clear the console
Replacing "cls" with "cmd \C cls" only opened a new command prompt, cleared it, and closed it without accessing the current console. How do I make a Java program running through Windows Command Prompt access the command prompt's arguments and use them to clear its output?
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
Solved here: Java: Clear the console
I realize this is an old post, but I hate when I find questions with responses of never mind i got it, or it just dies off. Hopefully it helps someone as it did for me.
Keep in mind it won't work in eclipse, but will in the regular console. take it a step further with if you're worried about cross OS:
final String os = System.getProperty("os.name");
if (os.contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
public static void clrscr(){
//Clears Screen in java
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
There's pretty much nothing in the console related API to do a clear screen. But, you can achieve the same effect through println()s. A lot of putty clients clear the page like that and then scroll up.
private static final int PAGE_SIZE = 25;
public static void main(String[] args) {
// ...
clearScreen();
}
private static void clearScreen() {
for (int i = 0; i < PAGE_SIZE; i++) {
System.out.println();
}
}
Create a batch file to clear the cmd screen and run your java program
Step 1. Create a file with extension .bat
Step 2. So your code in batch file will be
Cls
Cd desktop // path
Javac filename.java // compiling
Java desk // running
By doing this....you can clear the screen during run time
I am working on a program written in Java which, for some actions, launches external programs using user-configured command lines. Currently it uses Runtime.exec() and does not retain the Process reference (the launched programs are either a text editor or archive utility, so no need for the system in/out/err streams).
There is a minor problem with this though, in that when the Java program exits, it doesn't really quit until all the launched programs are exited.
I would greatly prefer it if the launched programs were completely independent of the JVM which launched them.
The target operating system is multiple, with Windows, Linux and Mac being the minimum, but any GUI system with a JVM is really what is desired (hence the user configurability of the actual command lines).
Does anyone know how to make the launched program execute completely independently of the JVM?
Edit in response to a comment
The launch code is as follows. The code may launch an editor positioned at a specific line and column, or it may launch an archive viewer. Quoted values in the configured command line are treated as ECMA-262 encoded, and are decoded and the quotes stripped to form the desired exec parameter.
The launch occurs on the EDT.
static Throwable launch(String cmd, File fil, int lin, int col) throws Throwable {
String frs[][]={
{ "$FILE$" ,fil.getAbsolutePath().replace('\\','/') },
{ "$LINE$" ,(lin>0 ? Integer.toString(lin) : "") },
{ "$COLUMN$",(col>0 ? Integer.toString(col) : "") },
};
String[] arr; // array of parsed tokens (exec(cmd) does not handle quoted values)
cmd=TextUtil.replace(cmd,frs,true,"$$","$");
arr=(String[])ArrayUtil.removeNulls(TextUtil.stringComponents(cmd,' ',-1,true,true,true));
for(int xa=0; xa<arr.length; xa++) {
if(TextUtil.isQuoted(arr[xa],true)) {
arr[xa]=TextDecode.ecma262(TextUtil.stripQuotes(arr[xa]));
}
}
log.println("Launching: "+cmd);
Runtime.getRuntime().exec(arr);
return null;
}
This appears to be happening only when the program is launched from my IDE. I am closing this question since the problem exists only in my development environment; it is not a problem in production. From the test program in one of the answers, and further testing I have conducted I am satisfied that it is not a problem that will be seen by any user of the program on any platform.
There is a parent child relation between your processes and you have to break that.
For Windows you can try:
Runtime.getRuntime().exec("cmd /c start editor.exe");
For Linux the process seem to run detached anyway, no nohup necessary.
I tried it with gvim, midori and acroread.
import java.io.IOException;
public class Exec {
public static void main(String[] args) {
try {
Runtime.getRuntime().exec("/usr/bin/acroread");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Finished");
}
}
I think it is not possible to to it with Runtime.exec in a platform independent way.
for POSIX-Compatible system:
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "your command"}).waitFor();
I have some observations that may help other people facing similar issue.
When you use Runtime.getRuntime().exec() and then you ignore the java.lang.Process handle you get back (like in the code from original poster), there is a chance that the launched process may hang.
I have faced this issue in Windows environment and traced the problem to the stdout and stderr streams. If the launched application is writing to these streams, and the buffer for these stream fills up then the launched application may appear to hang when it tries to write to the streams. The solutions are:
Capture the Process handle and empty out the streams continually - but if you want to terminate the java application right after launching the process then this is not a feasible solution
Execute the process call as cmd /c <<process>> (this is only for Windows environment).
Suffix the process command and redirect the stdout and stderr streams to nul using 'command > nul 2>&1'
It may help if you post a test section of minimal code needed to reproduce the problem. I tested the following code on Windows and a Linux system.
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec(args[0]);
}
}
And tested with the following on Linux:
java -jar JustForTesting.jar /home/monceaux/Desktop/__TMP/test.sh
where test.sh looks like:
#!/bin/bash
ping -i 20 localhost
as well as this on Linux:
java -jar JustForTesting.jar gedit
And tested this on Windows:
java -jar JustForTesting.jar notepad.exe
All of these launched their intended programs, but the Java application had no problems exiting. I have the following versions of Sun's JVM as reported by java -version :
Windows: 1.6.0_13-b03
Linux: 1.6.0_10-b33
I have not had a chance to test on my Mac yet. Perhaps there is some interaction occuring with other code in your project that may not be clear. You may want to try this test app and see what the results are.
You want to launch the program in the background, and separate it from the parent. I'd consider nohup(1).
I suspect this would require a actual process fork. Basically, the C equivalent of what you want is:
pid_t id = fork();
if(id == 0)
system(command_line);
The problem is you can't do a fork() in pure Java. What I would do is:
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
Runtime.getRuntime().exec(command);
}
catch(IOException e)
{
// Handle error.
e.printStackTrace();
}
}
});
t.start();
That way the JVM still won't exit, but no GUI and only a limited memory footprint will remain.
I tried everything mentioned here but without success. Main parent Java process can't quit until the quit of subthread even with cmd /c start and redirecting streams tu nul.
Only one reliable solution for me is this:
try {
Runtime.getRuntime().exec("psexec -i cmd /c start cmd.cmd");
}
catch (Exception e) {
// handle it
}
I know that this is not clear, but this small utility from SysInternals is very helpful and proven. Here is the link.
One way I can think of is to use Runtime.addShutdownHook to register a thread that kills off all the processes (you'd need to retain the process objects somewhere of course).
The shutdown hook is only called when the JVM exits so it should work fine.
A little bit of a hack but effective.