how to clear console in Java on Windows [duplicate] - java

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.

Related

VSCode not reading Cyrillic from console

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.

Java blinking cursor Ubuntu terminal

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??");
}

Run contents of string in java [duplicate]

This question already has answers here:
Run piece of code contained in a String
(9 answers)
Closed 6 years ago.
Lets say i have this String: String run = "System.out.println\(\"Hello\"\)". What i want to do is run what is in the string to output Hello in console.
Maybe there is a method like String.run()?
Try BeanShell , build your app with jar library.
import bsh.Interpreter;
private void runString(String code){
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context", this);//set any variable, you can refer to it directly from string
interpreter.eval(code);//execute code
}
catch (Exception e){//handle exception
e.printStackTrace();
}
}
Maybe in Java 9 you could use the REPL but as it's not there yet You would need to
* create a temporary file with a class with a know to You API
* run javac on it and compile it
* load the compiled class with a class loader
* run the code
If You want to do is running dynamically defined scripts in Your code then You could use Nashorn and JavaScript. It would do what You want. Also You could use Groovy in your project instead of Java - the syntax is similar to Java but Groovy is a dynamic language.
No, you cannot do it and there's no method to run this command in String. Anything withing the double quotes becomes String literals only and compiler doesn't take care of any command written in that.

Java check if program is installed on windows

Is there a way to check if a specific program is installed on Windows using Java?
I'm trying to develop a Java program that automatically creates zip archives by using the code line command from 7-Zip.
So, I would like to check in Java if on my windows OS '7-Zip' is already installed. No check for running apps or if OS is Windows or Linux. I want to get a bool (true/false) if '7-Zip' is installed on Windows.
The library Apache Commons has a class called SystemUtils - full documentation is available at https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html.
In this library you have the following static boolean properties at your disposal:
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The unix-like solution would be to simply try to run the program with --version flag (on windows probably the /? or - like in the 7zip case - without any at all) and check whether it fails, or what the return code will be.
Something like:
public boolean is7zipInstalled() {
try {
Process process = Runtime.getRuntime().exec("7zip.exe");
int code = process.waitFor();
return code == 0;
} catch (Exception e) {
return false;
}
}
I assume that you're talking about Windows. As Java is intended to be a platform-independent language and the way how to determine it differs per platform, there's no standard Java API to check that. You can however do it with help of JNI calls on a DLL which crawls the Windows registry. You can then just check if the registry key associated with the software is present in the registry. There's a 3rd party Java API with which you can crawl the Windows registry: jRegistryKey.
Here's an SSCCE with help of jRegistryKey:
package com.stackoverflow.q2439984;
import java.io.File;
import java.util.Iterator;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;
public class Test {
public static void main(String... args) throws Exception {
RegistryKey.initialize(Test.class.getResource("jRegistryKey.dll").getFile());
RegistryKey key = new RegistryKey(RootKey.HKLM, "Software\\Mozilla");
for (Iterator<RegistryKey> subkeys = key.subkeys(); subkeys.hasNext();) {
RegistryKey subkey = subkeys.next();
System.out.println(subkey.getName()); // You need to check here if there's anything which matches "Mozilla FireFox".
}
}
}
If you however intend to have a platformindependent application, then you'll also have to take into account the Linux/UNIX/Mac/Solaris/etc. (in other words: anywhere where Java is able to run) ways to detect whether FF is installed. Else you'll have to distribute it as a Windows-only application and do a System#exit() along with a warning whenever System.getProperty("os.name") is not Windows.
Sorry, I don't know how to detect in other platforms whether FF is installed or not, so don't expect an answer from me for that ;)

API throws java.io.UnsupportedEncodingException

I am developing a Java program in eclipse using a proprietary API and it throws the following exception at run-time:
java.io.UnsupportedEncodingException:
at java.lang.StringCoding.encode(StringCoding.java:287)
at java.lang.String.getBytes(String.java:954)...
my code:
private static String SERVER = "localhost";
private static int PORT = 80;
private static String DFT="";
private static String USER = "xx";
private static String pwd = "xx";
public static void main(String[] args) {
LLValue entInfo = new LLValue();
LLSession session = new LLSession(SERVER, PORT, DFT, USER, pwd);
try {
LAPI_DOCUMENTS doc = new LAPI_DOCUMENTS(session);
doc.AccessPersonalWS(entInfo);
} catch (Exception e) {
e.printStackTrace();
}
}
The session appears to open with no errors, but the encoding exception is thrown at doc.AccessEnterpriseWS(entInfo)
Through researching this error I have tried using the -encoding option of the compiler, changing the encoding of my editor, etc.
My questions are:
how can I find out the encoding of the .class files I am trying to use?
should I be matching the encoding of my new program to the encoding of the API?
If java is machine independent why isn't there standard encoding?
I have read this stack trace and this guide already --
Any suggestions will be appreciated!
Cheers
Run it in your debugger with a breakpoint on String.getBytes() or StringCoding.encode(). Both are classes in the JDK so you have access to them and should be able to see what the third party is passing in.
The character encoding is used to specify how to interpret the raw binary. The default encoding on English Windows systems in CP1252. Other languages and systems may use different a different default encoding. As a quick test, you might try specifying UTF-8 to see if the problem magically disappears.
As noted in this question, the JVM uses the default encoding of the OS, although you can override this default.
Without knowing more about the third party API you are trying to use, it's hard to say what encoding they might be using. Unfortunately from looking at the implementation of StringCoding.encode() it appears there are a couple different ways you could get an UnsupportedEncodingException. Stepping through with a debugger should help narrow things down.
It looks to me as if something in the proprietary API is calling String.getBytes with an empty string for the character set.
I compiled the following class
public class Test2 {
public static void main(String[] args) throws Exception {
"test".getBytes("");
}
}
and when I ran it, I got the following stacktrace:
Exception in thread "main" java.io.UnsupportedEncodingException:
at java.lang.StringCoding.encode(StringCoding.java:286)
at java.lang.String.getBytes(String.java:954)
at Test2.main(Test2.java:3)
I would be surprised if this is anything to do with the encoding in which the class files are written. It looks to me like this is a problem with code, not a problem you can fix by changing file encodings or compiler/JVM switches.
I don't know anything about what this proprietary API is supposed to do or how it works. Perhaps it is expecting to be run inside a Java EE or web application container? Perhaps it has a bug? Perhaps it needs more configuration before it can run without throwing exceptions? Given that it's proprietary, can you get any support from the vendor?

Categories

Resources